2013-06-16 1 views
1

나는 glade를 사용하여 guk로 gtk로 프로그램을 만들고 있습니다. 이 프로그램에는 몇 가지 메시지 대화 상자가 있습니다. 모든 사례에 대해 많은 메시지 대화 상자를 만들면 간단합니다. 그러나 하나의 메시지 대화 상자를 만들어 다른 텍스트로 다른 경우에 사용할 수 있습니까? 실제로는 간단합니다. 난 그냥 기본 텍스트를 변경하고 그것을 보여줄 필요가있다. 그러나 기본 텍스트 herehere을 변경하는 방법을 찾지 못했습니다.파이썬에서 gtk messagedialog의 기본 텍스트를 변경하는 방법?

아래는 샘플 코드입니다 : 나는 이런 식으로 뭔가로 변경할

from gi.repository import Gtk 

def clicked1(widget): 
    response = dialog1.run() 
    if response == Gtk.ResponseType.OK: 
     print 'ok' 
    else: 
     print 'cancel' 
     dialog1.destroy() 

def clicked2(widget): 
    response = dialog2.run() 
    if response == Gtk.ResponseType.OK: 
     print 'ok' 
    else: 
     print 'cancel' 
     dialog2.destroy() 

def clicked3(widget): 
    response = dialog3.run() 
    if response == Gtk.ResponseType.OK: 
     print 'ok' 
    else: 
     print 'cancel' 
     dialog3.destroy() 

builder = Gtk.Builder() 
builder.add_from_file('gui.glade') 
dialog1 = builder.get_object('dialog1') 
dialog2 = builder.get_object('dialog2') 
dialog3 = builder.get_object('dialog3') 
builder.get_object('button1').connect('clicked', clicked1) 
builder.get_object('button2').connect('clicked', clicked2) 
builder.get_object('button3').connect('clicked', clicked3) 
builder.get_object('window1').show_all() 
Gtk.main() 

from gi.repository import Gtk 

def clicked1(widget): 
    **dialog.set_text(1)** 
    response = dialog.run() 
    if response == Gtk.ResponseType.OK: 
     print 'ok' 
    else: 
     print 'cancel' 
     dialog.destroy() 

def clicked2(widget): 
    **dialog.set_text(2)** 
    response = dialog.run() 
    if response == Gtk.ResponseType.OK: 
     print 'ok' 
    else: 
     print 'cancel' 
     dialog.destroy() 

def clicked3(widget): 
    **dialog.set_text(3)** 
    response = dialog.run() 
    if response == Gtk.ResponseType.OK: 
     print 'ok' 
    else: 
     print 'cancel' 
     dialog.destroy() 

builder = Gtk.Builder() 
builder.add_from_file('gui.glade') 
**dialog = builder.get_object('dialog')** 
builder.get_object('button1').connect('clicked', clicked1) 
builder.get_object('button2').connect('clicked', clicked2) 
builder.get_object('button3').connect('clicked', clicked3) 
builder.get_object('window1').show_all() 
Gtk.main() 

답변

1

초기화 후 gtk_message_dialog의 텍스트를 새로에는 직접 방법이없는 것 같다, 그러나 메시지 대화 상자는 상자, 레이블, 이미지 및 단추의 조합이기 때문에 메시지 대화 상자에서 기본/보조 텍스트를 수정/새로 고치는 추악한 방법입니다.

labels = dialog_info.get_children()[0].get_children()[0].get_children()[1].get_children()

이 데모의

전체 소스 코드는 여기 :

#!/usr/bin/env python3 

from gi.repository import Gtk 

class Handler: 
    def __init__(self, builder): 
     self.builder = builder 
     self.window = builder.get_object('window1') 

    def run(self): 
     self.window.show_all() 
     Gtk.main() 

    def on_app_exit(self, widget, event=None): 
     Gtk.main_quit() 

    def on_button_show_clicked(self, btn): 
     dialog_info = self.builder.get_object('messagedialog_info') 
     entry = self.builder.get_object('entry1') 
     labels = dialog_info.get_children()[0].get_children()[0].get_children()[1].get_children() 
     print(labels) 
     # labels[0] is the primary label. 
     # labels[1] is the seconary label. 
     labels[0].set_text(entry.get_text()) 

     response = dialog_info.run() 
     print('response: ', response) 
     dialog_info.hide() 


def main(): 
    builder = Gtk.Builder() 
    builder.add_from_file('example.glade') 
    handler = Handler(builder) 
    builder.connect_signals(handler) 
    handler.run() 

if __name__ == '__main__': 
    main() 

과 숲 사이의 빈터 파일 'example.glade'또는

<?xml version="1.0" encoding="UTF-8"?> 
<interface> 
    <!-- interface-requires gtk+ 3.0 --> 
    <object class="GtkMessageDialog" id="messagedialog_info"> 
    <property name="can_focus">False</property> 
    <property name="border_width">5</property> 
    <property name="type_hint">dialog</property> 
    <property name="skip_taskbar_hint">True</property> 
    <property name="buttons">close</property> 
    <property name="text" translatable="yes">hello text</property> 
    <property name="secondary_text" translatable="yes">hello secondary text.</property> 
    <child internal-child="vbox"> 
     <object class="GtkBox" id="messagedialog-vbox"> 
     <property name="can_focus">False</property> 
     <property name="orientation">vertical</property> 
     <property name="spacing">2</property> 
     <child internal-child="action_area"> 
      <object class="GtkButtonBox" id="messagedialog-action_area"> 
      <property name="can_focus">False</property> 
      <property name="layout_style">end</property> 
      <child> 
       <placeholder/> 
      </child> 
      <child> 
       <placeholder/> 
      </child> 
      </object> 
      <packing> 
      <property name="expand">False</property> 
      <property name="fill">True</property> 
      <property name="pack_type">end</property> 
      <property name="position">0</property> 
      </packing> 
     </child> 
     </object> 
    </child> 
    </object> 
    <object class="GtkWindow" id="window1"> 
    <property name="can_focus">False</property> 
    <property name="border_width">5</property> 
    <signal name="delete-event" handler="on_app_exit" swapped="no"/> 
    <child> 
     <object class="GtkBox" id="box1"> 
     <property name="visible">True</property> 
     <property name="can_focus">False</property> 
     <property name="valign">center</property> 
     <property name="spacing">5</property> 
     <child> 
      <object class="GtkEntry" id="entry1"> 
      <property name="visible">True</property> 
      <property name="can_focus">True</property> 
      <property name="invisible_char">●</property> 
      </object> 
      <packing> 
      <property name="expand">True</property> 
      <property name="fill">True</property> 
      <property name="position">0</property> 
      </packing> 
     </child> 
     <child> 
      <object class="GtkButton" id="button_show"> 
      <property name="label" translatable="yes">_Show</property> 
      <property name="use_action_appearance">False</property> 
      <property name="visible">True</property> 
      <property name="can_focus">True</property> 
      <property name="receives_default">True</property> 
      <property name="use_action_appearance">False</property> 
      <property name="use_underline">True</property> 
      <signal name="clicked" handler="on_button_show_clicked" swapped="no"/> 
      </object> 
      <packing> 
      <property name="expand">False</property> 
      <property name="fill">True</property> 
      <property name="position">1</property> 
      </packing> 
     </child> 
     </object> 
    </child> 
    </object> 
</interface> 
+0

나는 이것을 도와 주셔서 감사합니다. – user2435611

+0

두 개의 라벨이 들어있는 상자를 반환하는'gtk_message_dialog_get_message_area()'를 사용하여 간단한 방법을 발견했습니다. :) – LiuLang

+0

및 기본 텍스트 레이블에 액세스하는 방법? – user2435611

2

, 우리가 gtk_message_dialog의 일부 포장 기능을 쓸 수 있습니다 다음은 간단한 예입니다.

def info(text, text2=None): 
    dialog = Gtk.MessageDialog(None, 
      Gtk.DialogFlags.MODAL, 
      Gtk.MessageType.INFO, 
      Gtk.ButtonsType.OK, 
      text) 
    if text2 != None: 
     dialog.format_secondary_text(text2) 
    response = dialog.run() 
    dialog.destroy() 

문제는 부모 창을 메시지 대화 상자에서 구체화하지 않으면 프로그램 중심이 아닌 화면 중앙에 표시됩니다. 이 문제를 해결하기 위해 클래스에 info() 함수를 넣고 부모 창 매개 변수를 설정할 수 있습니다.

경고, 질문 및 오류와 같은 다른 유형의 메시지도 같은 방식으로 처리 할 수 ​​있습니다.

그리고 작은 데모 : 메시지 대화 상자의

#!/usr/bin/env python3 

from gi.repository import Gtk 

def info(text, text2=None): 
    dialog = Gtk.MessageDialog(None, 
      Gtk.DialogFlags.MODAL, 
      Gtk.MessageType.INFO, 
      Gtk.ButtonsType.OK, 
      text) 
    if text2 != None: 
     dialog.format_secondary_text(text2) 
    response = dialog.run() 
    dialog.destroy() 

def error(text, text2=None): 
    ''' 
    TODO 
    ''' 
    pass 

def main(): 
    win = Gtk.Window() 
    win.connect('delete-event', Gtk.main_quit) 
    win.show_all() 
    info('hello') 
    info('hello, primary text', 'hello secondary text') 

    Gtk.main() 

if __name__ == '__main__': 
    main() 

위젯의 구조는 다음과 같다 : enter image description here

1

어쩌면 조금 너무 늦게, 그러나 나는 같은 일을 찾고 있었고, 난 할 수 GtkMessageDialog 미리 작성된 메소드를 호출하지 않고도 기본 텍스트와 보조 텍스트를 간단하면서도 효율적으로 변경할 수 있습니다.

사전 작성된 메소드 "set_markup"및 "format_secondary_text"를 호출하지 않고 이러한 텍스트를 변경하는 것이 더 쉽지 않은지 이해하려고했습니다. "format_secondary_text"가 매력처럼 작동하여 사실상 두 번째 텍스트를 완벽하게 변경하더라도 "set_markup"은 기본 텍스트를 변경하지만 두 번째 텍스트가있는 상태에서 제목으로 인식되지 않기 때문에 그렇지 않습니다. 굵게 표시되지만 일부 PANGO 마크 업을 기다리고 있습니다. 그렇지 않으면 간단한 굵은 텍스트가 아닙니다.

그럼 난 그냥 모든 메소드, 속성을 살펴보고 그래서 그 GtkMessageDialog에 사용할 수있는 유휴 열고 내가 아래에 붙여 넣기로 내가 뭔가를 발견

import gi 
gi.require_version('Gtk', '3.0') 
from gi.repository import Gtk 
builder = Gtk.Builder() 
#any Glade file with at least 1 GtkMessageDialog 
builder.add_from_file("myFile.glade") 
#The ID of GtkMessageDialog in Glade 
myDialog = builder.get_object("GtkMessageDialog1") 

#Below I change primary and secondary texts before running the Dialog. 
myDialog.set_property("text","Hello World") 
myDialog.set_property("secondary_text","Here I go again.") 

myDialog.run() 
myDialog.hide() 

그냥 I로 주목 Python 2.7을 사용하여 작성했지만 원칙은 Python 3.x와 동일해야합니다.