PythonGtk : expand NoteBook to fill the rest of my window - python

I am trying to resize my window using Python Gtk3, but I need to expand the Notebook object to fill the main window.
How could I make the notebook fill the rest of the window?
Like this:
Here is my code :
#!/usr/bin/python
# coding=utf-8
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
class SearchDialog(Gtk.Dialog):
def __init__(self, parent):
Gtk.Dialog.__init__(self, "Something", parent,
Gtk.DialogFlags.MODAL, buttons=(
Gtk.STOCK_NEW, Gtk.ResponseType.OK,
Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL))
self.set_default_size(400, 600)
box = self.get_content_area()
label = Gtk.Label("Insert text you want to search for:")
box.add(label)
# self.entry = Gtk.Entry()
# box.add(self.entry)
self.main_area = Gtk.Stack()
self.main_area.set_transition_type(Gtk.StackTransitionType.SLIDE_LEFT_RIGHT)
self.main_area.set_transition_duration(1000)
self.entry = Gtk.Entry()
self.main_area.add_titled(self.entry, "entry_name", "Entry Url")
self.labelS = Gtk.Label()
self.label_txt = """<big><i> label here</i></big>"""
self.labelS.set_markup(self.label_txt)
self.labelS.set_line_wrap(True)
self.main_area.add_titled(self.labelS, "label_name", "How Scan will Start")
self.our_stackSwitcher = Gtk.StackSwitcher()
self.our_stackSwitcher.set_stack(self.main_area)
box.add(self.our_stackSwitcher)
box.add(self.main_area)
self.show_all()
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Desktop app title")
self.set_default_size(1000, 648)
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
self.add(vbox)
Hbox1 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
vbox.add(Hbox1)
Hbox2 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
vbox.add(Hbox2)
Hbox3 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
vbox.add(Hbox3)
Hbox4 = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
vbox.add(Hbox4)
main_menu_bar = Gtk.MenuBar()
#################################################################################
#drop down the menu
file_menu1 = Gtk.Menu()
file_menu1_dropdown = Gtk.MenuItem("File")
#File menu Items
file_new = Gtk.MenuItem("New Scan")
file_save = Gtk.MenuItem("Save History")
file_exit = Gtk.MenuItem("Exit")
file_menu1_dropdown.set_submenu(file_menu1)
file_menu1.append(file_new)
file_new.connect("activate", self.Onclick_new)
file_menu1.append(file_save)
file_save.connect("activate", self.Onclick_save)
file_menu1.append(Gtk.SeparatorMenuItem())
file_menu1.append(file_exit)
file_exit.connect("activate",self.Onclick_exit)
#add the menu to the main menu bar
main_menu_bar.append(file_menu1_dropdown)
###################################################################################
#drop down the menu
file_menu2 = Gtk.Menu()
file_menu2_dropdown = Gtk.MenuItem("Scan")
#File menu Items
file_edit = Gtk.MenuItem("Edit")
file_cancel = Gtk.MenuItem("Cancel")
file_menu2_dropdown.set_submenu(file_menu2)
file_menu2.append(file_edit)
file_edit.connect("activate", self.Onclick_edit)
file_menu2.append(file_cancel)
file_cancel.connect("activate", self.Onclick_cancel)
#add the menu to the main menu bar
main_menu_bar.append(file_menu2_dropdown)
###################################################################################
#drop down the menu
file_menu3 = Gtk.Menu()
file_menu3_dropdown = Gtk.MenuItem("Help")
#File menu Items
file_mode = Gtk.MenuItem("Mode")
file_about = Gtk.MenuItem("About")
file_menu3_dropdown.set_submenu(file_menu3)
file_menu3.append(file_mode)
file_mode.connect("activate", self.Onclick_mode)
file_menu3.append(file_about)
file_about.connect("activate", self.Onclick_about)
#add the menu to the main menu bar
main_menu_bar.append(file_menu3_dropdown)
###################################################################################
## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ##
Hbox1.pack_start(main_menu_bar , True, True, 0)
label1_Hbox2 = Gtk.Label(" i am label 1 of Horizental box 2")
Hbox2.pack_start(label1_Hbox2 , True, True, 0)
label2_Hbox2 = Gtk.Label(" i am label 2 of Horizental box 2")
Hbox2.pack_start(label2_Hbox2, True, True, 0)
self.notebook1 = Gtk.Notebook()
Hbox3.pack_start(self.notebook1, True, True, 0)
self.notebook2 = Gtk.Notebook()
Hbox3.pack_start(self.notebook2, True, True, 0)
##################################################################################################
self.page1 = Gtk.Box()
self.page1.set_border_width(3)
self.label = Gtk.Label('label Number 1-------')
self.page1.add(self.label)
self.label2 = Gtk.Label('label Number 2 should appear in next line')
self.page1.add(self.label2)
self.notebook1.append_page(self.page1, Gtk.Label('Tab Pane 1 panel 1'))
###################################################################################################
self.page1 = Gtk.Box()
self.notebook2.append_page(self.page1, Gtk.Label('Tab Pane 1 panel 2'))
self.page2 = Gtk.Box()
self.notebook2.append_page(self.page2, Gtk.Label('Tab Pane 2 panel 2'))
def Onclick_new(self, widget):
dialog = SearchDialog(self)
response = dialog.run()
if response == Gtk.ResponseType.OK:
self.label.set_text(dialog.entry.get_text())
dialog.destroy()
def Onclick_save(self, widget):
print("Save clicked")
def Onclick_exit(self, widget):
print("exit clicked")
Gtk.main_quit()
def Onclick_edit(self, widget):
print("Edit clicked")
def Onclick_cancel(self, widget):
print("Cancel clicked")
def Onclick_mode(self, widget):
print("Mode of use clicked")
def Onclick_about(self, widget):
print("About clicked")
#cssProvider = Gtk.CssProvider()
#cssProvider.load_from_path('gtkStyledButtonTest.css')
#screen = Gdk.Screen.get_default()
#styleContext = Gtk.StyleContext()
#styleContext.add_provider_for_screen(screen, cssProvider,
# Gtk.STYLE_PROVIDER_PRIORITY_USER)
win = MyWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

Related

A customized menu bar without using the widget tk.Menu

I would like to personalized a menu bar. For example I want to delete the border that appears around the tk.Menu widget (with the add_command() method)
That's my code (I'm using Windows 10)
import tkinter as tk
from tkinter import ttk
dark_grey = "#212121"
dark_blue="#102A43"
blue_1="#243B53"
root = tk.Tk()
root.state('zoomed')
container = tk.Frame(root, bg = dark_grey)
container.grid_rowconfigure(0, weight = 0)
container.grid_columnconfigure(0, weight = 1)
menu_frame = tk.Frame(container, bg = dark_blue)
menu1 = tk.Menubutton(menu_frame, text = "Menu1", bg = dark_blue, fg =
"white", activebackground = blue_1, activeforeground =
"white")
menu1.grid(row = 0, column = 0)
submenu1 = tk.Menu(menu1, tearoff = 0, bg = dark_blue,
activebackground= blue_1, fg = "white",borderwidth = 0, activeborderwidth= 0)
submenu1.add_command(label = "Option 1.1")
submenu1.add_command(label = "Option 1.2")
menu1.configure(menu = submenu1)
menu_frame.grid(row = 0, column = 0, sticky = "ew")
container.pack(fill = tk.BOTH, expand = "True")
root.mainloop()
My idea is to create a menu without using tk.Menu and tk.MenuButton. I would like "bind" an <Enter> event to a label, in order to create a sort of drop down under the label. Is it possible?
Question: Customized menu bar without using the widget tk.Menu?
This example uses a tk.Toplevel as a popup window and displays the added tk.Menubutton.
The Submenu follows ths defined Style of the Top tk.Menubutton.
TODO:
Close the Popup Window if clicked outside or another Top Menubutton.
Extend with other than only tk.Menubutton
Keyboard support
import tkinter as tk
class Menu:
def __init__(self, parent, **kwargs):
self._popup = None
self._menubutton = []
self.parent = parent
self.parent.bind('<Button-1>', self.on_popup)
def on_popup(self, event):
w = event.widget
x, y, height = self.parent.winfo_rootx(), self.parent.winfo_rooty(), self.parent.winfo_height()
self._popup = tk.Toplevel(self.parent.master, bg=self.parent.cget('bg'))
self._popup.overrideredirect(True)
self._popup.geometry('+{}+{}'.format(x, y + height))
for kwargs in self._menubutton:
self._add_command(**kwargs)
def add_command(self, **kwargs):
self._menubutton.append(kwargs)
def _add_command(self, **kwargs):
command = kwargs.pop('command', None)
menu = self.parent
mb = tk.Menubutton(self._popup, text=kwargs['label'],
bg=menu.cget('bg'),
fg=menu.cget('fg'),
activebackground=menu.cget('activebackground'),
activeforeground=menu.cget('activeforeground'),
borderwidth=0,
)
mb._command = command
mb.bind('<Button-1>', self._on_command)
mb.grid()
def _on_command(self, event):
w = event.widget
print('_on_command("{}")'.format(w.cget('text')))
self._popup.destroy()
if w._command is not None:
w._command()
Usage:
class App(tk.Tk):
def __init__(self):
super().__init__()
self.geometry("200x200")
style = {'bg': "#102A43", 'fg': "white",
'activebackground': "#243B53", 'activeforeground': "white",
'borderwidth': 0}
menu1 = tk.Menubutton(self, text="Menu1", **style)
submenu1 = Menu(menu1)
submenu1.add_command(label="Option 1.1")
submenu1.add_command(label="Option 1.2")
menu1.grid(row=0, column=0)
menu2 = tk.Menubutton(self, text="Menu2", **style)
submenu2 = Menu(menu2)
submenu2.add_command(label="Option 2.1")
submenu2.add_command(label="Option 2.2")
menu2.grid(row=0, column=2)
if __name__ == "__main__":
App().mainloop()
Tested with Python: 3.5 - 'TclVersion': 8.6 'TkVersion': 8.6

How do I use keyboard shortcuts with Gtk StackSwitcher?

What I want to do is make a shortcut keyboard key to switch between Page 1 and Page 2. For instance, pressing Ctrl+S would take me to Page 1 if I am not already there and likewise pressing Ctrl+R would take me to Page 2. I searched the documentation but I couldn't find anything related to what I need. Is there a way to implement it? Please see the below image:
Stack Switcher
Here's the snippet:
class App(Gtk.Application):
def __init__(self, *args, **kwargs):
super(App, self).__init__(*args, **kwargs)
self.connect('activate', self.on_activate)
self.send_stack = None
self.receive_stack = None
self.send_receive_stack = None
self.header_button_handler_id = None
self.pre_sign_widget = None
def on_activate(self, app):
ui_file_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"app.ui")
appwindow = 'applicationwindow1'
builder = Gtk.Builder()
builder.add_objects_from_file(ui_file_path, [appwindow])
window = builder.get_object(appwindow)
window.set_wmclass ("sign", "sign")
window.set_title("sign")
window.connect("delete-event", self.on_delete_window)
self.headerbar = window.get_titlebar()
self.header_button = builder.get_object("back_refresh_button")
self.header_button.connect('clicked', self.on_header_button_clicked)
sw = builder.get_object('stackswitcher1')
# I want to be able to press Alt+S and Alt+R respectively
# to switch the stack pages to Send and Receive.
# sw.get_children()
self.stack_switcher = sw
self.send_receive_stack = builder.get_object("send_receive_stack")
self.send_receive_stack.connect('notify::visible-child',
self.on_sr_stack_switch)
## Load Send part
self.send = SendApp()
ss = self.send.stack
p = ss.get_parent()
if p:
p.remove(ss)
ss.connect('notify::visible-child', self.on_send_stack_switch)
ss.connect('map', self.on_send_stack_mapped)
klw = self.send.klw
klw.connect("key-activated", self.on_key_activated)
klw.connect("map", self.on_keylist_mapped)
klw.props.margin_left = klw.props.margin_right = 15
self.send_stack = ss
## End of loading send part
# Load Receive part
self.receive = PswMappingReceiveApp(self.on_presign_mapped)
rs = self.receive.stack
rs.connect('notify::visible-child',
self.on_receive_stack_switch)
scanner = self.receive.scanner
scanner.connect("map", self.on_scanner_mapped)
self.receive_stack = rs
self.send_receive_stack.add_titled(self.send_stack,
"send_stack", _("Send"))
self.send_receive_stack.add_titled(rs,
"receive_stack", _("Receive"))
accel_group = Gtk.AccelGroup()
window.add_accel_group(accel_group)
self.receive.accept_button.add_accelerator("clicked", accel_group, ord('o'), Gdk.ModifierType.MOD1_MASK,
Gtk.AccelFlags.VISIBLE)
self.receive.accept_button.set_can_default(True)
window.show_all()
self.add_window(window)
Here's a hacky way to get to the first and last children of a stack with two children:
#!/usr/bin/env python
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GdkPixbuf, Gdk
import os, sys
class GUI:
def __init__(self):
self.stack = Gtk.Stack()
switcher = Gtk.StackSwitcher()
switcher.set_stack(self.stack)
label1 = Gtk.Label("label 1")
label2 = Gtk.Label("label 2")
label3 = Gtk.Label("label 3")
self.stack.add_titled (label1, "1", "Page 1")
self.stack.add_titled (label2, "2", "Page 2")
self.stack.add_titled (label3, "3", "Page 3")
box = Gtk.Box()
box.pack_start(switcher, True, False, 0)
box.pack_start(self.stack, True, True, 0)
box.set_orientation(Gtk.Orientation.VERTICAL)
window = Gtk.Window()
window.add(box)
window.show_all()
window.connect("key-press-event", self.key_press)
def key_press (self, window, event):
keyname = Gdk.keyval_name(event.keyval)
if not Gdk.ModifierType.CONTROL_MASK:
#only continue when the CTRL key is down
return
#get the last child
if keyname == "r":
for child in self.stack.get_children():
self.stack.set_visible_child(child)
#get the first child
if keyname == "s":
for child in self.stack.get_children():
self.stack.set_visible_child(child)
return
def on_window_destroy(self, window):
Gtk.main_quit()
def main():
app = GUI()
Gtk.main()
if __name__ == "__main__":
sys.exit(main())
Here's a hacky way to scroll forward and backward through a stack with more than two children:
#!/usr/bin/env python
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GdkPixbuf, Gdk
import os, sys
class GUI:
def __init__(self):
self.stack = Gtk.Stack()
switcher = Gtk.StackSwitcher()
switcher.set_stack(self.stack)
label1 = Gtk.Label("label 1")
label2 = Gtk.Label("label 2")
label3 = Gtk.Label("label 3")
self.stack.add_titled (label1, "1", "Page 1")
self.stack.add_titled (label2, "2", "Page 2")
self.stack.add_titled (label3, "3", "Page 3")
box = Gtk.Box()
box.pack_start(switcher, True, False, 0)
box.pack_start(self.stack, True, True, 0)
box.set_orientation(Gtk.Orientation.VERTICAL)
window = Gtk.Window()
window.add(box)
window.show_all()
window.connect("key-press-event", self.key_press)
def key_press (self, window, event):
keyname = Gdk.keyval_name(event.keyval)
if not Gdk.ModifierType.CONTROL_MASK:
#only continue when the CTRL key is down
return
#forward scroll
#variable to capture the active widget
previous_child_active = False
if keyname == "r":
#iterate over the stack children
for child in self.stack.get_children():
if previous_child_active == True:
# the last widget was the one that was active
self.stack.set_visible_child(child)
#finished
return
#remember if the previous child was active
previous_child_active = self.stack.get_visible_child() == child
#reverse scroll
#variable to capture the last widget we iterated
previous_child = None
if keyname == "s":
#iterate over the stack children
for child in self.stack.get_children():
if self.stack.get_visible_child() == child and previous_child != None:
#this is the active widget, so we set the previous active
self.stack.set_visible_child(previous_child)
#finished
return
#remember the last widget
previous_child = child
def on_window_destroy(self, window):
Gtk.main_quit()
def main():
app = GUI()
Gtk.main()
if __name__ == "__main__":
sys.exit(main())

Python Gtk - set_visible works temperamentally

I have a window which has two dropdown lists (country and club) which should never be visible at the same time.
When the app loads, neither should be visible. A third dropdown list (tournament type), with nothing selected by default, decides which of the club or country lists should display. Clicking on a button at the top of the screen populates the dropdown lists, selecting the appropriate tournament type and the associated club/or country.
What actually happens: When it loads, both dropdown lists are visible. When the tournament type is selected, both lists are visible. When I click the button at the top the club list is available and the country list is not. The latter is exactly as it should be.
I'm using the same function (set_visible()) to show or hide the lists in each case so I'm at a loss as to why it works in one case but not in the other two.
The code below should run. The bit after #Add Tournaments Tab creates the widgets and unsuccessfully tries to hide the combo boxes. The function on_type_combo changed unsuccessfully tries to hide one of the combo boxes. The function on_tournament_details successfully hides the appropriate box.
#!/usr/bin/python
# coding=utf-8
from gi.repository import Gtk
import wikipedia
class NotebookWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="Rugby Database")
#Initialise data
self.country_store = Gtk.ListStore(int, str, str)
self.club_store = Gtk.ListStore(int, str, str, int, int)
self.tournament_store = Gtk.ListStore(int, str, int, str, int)
self.cur_id = 0
self.cur_club = ''
self.cur_club_id = 0
self.update_club_id = 0
self.update_tournament_id = 0
self.initialise_lists()
#Create Application Window
self.set_border_width(10)
self.set_default_size(800, 600)
self.set_position(Gtk.WindowPosition.CENTER)
#Add external container (box)
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
self.add(vbox)
#Add tabbed window
self.nbook = Gtk.Notebook()
vbox.pack_start(self.nbook, True, True, 0)
self.nbook.show()
#Add Tournaments tab
frame = Gtk.Frame()
frame.show()
self.t_type_id = -1
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
self.tournament_box = Gtk.FlowBox()
self.tournament_box.set_valign(Gtk.Align.START)
self.tournament_box.set_max_children_per_line(4)
self.tournament_box.set_selection_mode(Gtk.SelectionMode.SINGLE)
self.tournament_box.set_activate_on_single_click(True)
vbox.pack_start(self.tournament_box, True, True, 0)
self.wiki_label = Gtk.Label()
self.wiki_label.set_line_wrap(True)
vbox.add(self.wiki_label)
tournament_grid = Gtk.Grid()
tournament_grid.set_column_spacing(5)
tournament_label = Gtk.Label(" Tournament Name: ")
tournament_logo_label = Gtk.Label("Logo:")
self.tournament_logo_entry = Gtk.Entry()
self.tournament_entry = Gtk.Entry()
self.t_type_combo = Gtk.ComboBoxText()
self.t_holder_combo_country = Gtk.ComboBoxText()
self.t_holder_combo_club = Gtk.ComboBoxText()
self.t_holder_combo_country = Gtk.ComboBox.new_with_model(self.country_store)
renderer_text = Gtk.CellRendererText()
self.t_holder_combo_country.pack_start(renderer_text, True)
self.t_holder_combo_country.add_attribute(renderer_text, "text", 1)
self.t_holder_combo_club = Gtk.ComboBox.new_with_model(self.club_store)
renderer_text = Gtk.CellRendererText()
self.t_holder_combo_club.pack_start(renderer_text, True)
self.t_holder_combo_club.add_attribute(renderer_text, "text", 1)
self.t_type_combo.append_text("Club")
self.t_type_combo.append_text("International")
self.t_type_combo.connect("changed", self.on_type_combo_changed)
renderer_text = Gtk.CellRendererText()
self.t_type_combo.pack_start(renderer_text, True)
self.t_type_combo.add_attribute(renderer_text, "text", 1)
type_label = Gtk.Label(" Type: ")
holder_label = Gtk.Label(" Holder: ")
tournament_add = Gtk.Button(" Save ")
tournament_grid.add(tournament_label)
tournament_grid.add(self.tournament_entry)
tournament_grid.add(type_label)
tournament_grid.add(self.t_type_combo)
tournament_grid.add(tournament_logo_label)
tournament_grid.add(self.tournament_logo_entry)
tournament_grid.add(holder_label)
tournament_grid.add(self.t_holder_combo_club)
tournament_grid.add(self.t_holder_combo_country)
tournament_grid.add(tournament_add)
vbox.add(tournament_grid)
self.t_holder_combo_club.set_visible(False)
self.t_holder_combo_country.set_visible(False)
self.tournament_message = Gtk.Label("\n")
vbox.add(self.tournament_message)
label = Gtk.Label()
label.set_markup("<b><big>Tournaments</big></b>")
frame.add(vbox)
self.nbook.append_page(frame, label)
self.load_boxes()
##### Function definitions #####
def initialise_lists(self):
self.country_store.clear()
self.country_store.append([1, 'Ireland', ''])
self.club_store.clear()
self.club_store.append([1, 'Leinster', '',1,1])
self.tournament_store.clear()
self.tournament_store.append([1, 'Pro 12', 1,'',1])
def reset_forms(self):
self.tournament_entry.set_text('')
self.update_club_id = 0
self.update_tournament_id = 0
self.tournament_entry.set_text('')
self.tournament_logo_entry.set_text('')
self.wiki_label.set_text('\n')
def load_boxes(self):
self.tournament_box.foreach(lambda widget: self.tournament_box.remove(widget))
for tournament in range(0, len(self.tournament_store)):
button = Gtk.Button(self.tournament_store[tournament][1])
self.tournament_box.add(button)
button.connect('clicked', self.on_tournament_details, tournament)
self.tournament_box.show_all()
def on_club_combo_changed(self, combo):
tree_iter = combo.get_active_iter()
if tree_iter is not None:
model = combo.get_model()
self.cur_club_id = model[tree_iter][0]
def on_type_combo_changed(self, combo):
tree_iter = combo.get_active_iter()
if tree_iter is not None:
model = combo.get_model()
self.t_type_id = model[tree_iter][0]
if self.t_type_id is "Club":
self.t_holder_combo_country.set_visible(False)
self.t_holder_combo_club.set_visible(True)
elif self.t_type_id is "International":
self.t_holder_combo_club.set_visible(False)
self.t_holder_combo_country.set_visible(True)
def on_tournament_details(self, button, tournament):
self.tournament_entry.set_text(self.tournament_store[tournament][1])
self.t_type_combo.set_active(self.tournament_store[tournament][2]-1)
self.tournament_logo_entry.set_text(self.tournament_store[tournament][3])
self.update_tournament_id = self.tournament_store[tournament][0]
self.tournament_message.set_text('\n')
self.wiki_label.set_text(wikipedia.summary(self.tournament_store[tournament][1], sentences=2))
if self.t_type_id == "Club":
self.t_holder_combo_country.set_visible(False)
self.t_holder_combo_club.set_visible(True)
self.t_holder_combo_club.set_active(self.tournament_store[tournament][4]-1)
elif self.t_type_id == "International":
self.t_holder_combo_club.set_visible(False)
self.t_holder_combo_country.set_visible(True)
self.t_holder_combo_country.set_active(self.tournament_store[tournament][4]-1)
win = NotebookWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
Tell the dropdown lists not to show, when you call win.show_all(). This can be accomblished by calling set_no_show_all on the widget, that should not be shown.

How to disable the close button in GTK?

I have created a One Time Password mechanism in OpenERP 6.0.3's GTK client. After login the GTK client shows a window to enter the One Time Password as below.
Now I want to disable the close button at the top left of the window. How can I do that? I am using python and the code to create the window is:
EDIT
class sms_auth(gtk.Dialog):
def run_thread(self):
code=self.textbox_code.get_text()
self.result = rpc.session.rpc_exec_auth('/object', 'execute', 'res.users', 'check_code', code)
return self.result
def run(self):
self.show_all()
res = super(sms_auth, self).run()
result = None
if res == gtk.RESPONSE_ACCEPT:
result = self.run_thread()
self.destroy()
return result
def hide(*args):
window.hide()
return gtk.TRUE
def __init__(self, parent, response):
# To use cancel butto add gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
gtk.Dialog.__init__(
self, 'Sms Authentication', parent,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)
)
label = gtk.Label("Please enter sms code :")
self.parent_widget = parent
self.response = False
self.db_login_response = response
self.connect('delete_event', hide)
self.textbox_code = gtk.Entry()
label.set_alignment(0,0)
table = gtk.Table(1, 7)
table.set_homogeneous(False)
table.set_col_spacings(40)
table.attach(label, 0, 6, 0, 1, ypadding=4)
table.attach(self.textbox_code, 5, 6, 0, 1, ypadding=4)
self.vbox.pack_start(table,False, False, 0)
Try like this
def hide(self, *args):
window.hide()
return gtk.TRUE
self.window.connect('delete_event', self.hide)
Note: Refer here
import pygtk
pygtk.require('2.0')
import gtk
class DialogExample(gtk.Dialog):
def __init__(self, parent=None):
gtk.Dialog.__init__(self, "My Dialog", parent,
gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
(gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)
)
self.set_default_size(150, 100)
label = gtk.Label("This is a dialog to display additional information")
box = self.get_content_area()
box.add(label)
self.show_all()
self.connect('delete-event', self.delete_event)
def delete_event(self, widget, event=None):
print "Here"
return True
def main():
# rest in gtk_main and wait for the fun to begin!
gtk.main()
return 0
if __name__ == "__main__":
DialogExample()
main()

How to combine numerous programs into one code?

I have a program that opens numerous other programs.
How can I combine the code from the other programs into this code so that instead of 10 sets of code i will only have one?
Code for app that I want to put all the codes in:
import pygtk
pygtk.require('2.0')
import gtk
import subprocess
class Example:
def __init__(self):
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_size_request(600, 600)
window.set_title("GTK Menu")
window.connect("delete_event",
lambda w,e: gtk.main_quit())
# Add Vbox so that we can have numerous widgets
vbox = gtk.VBox(False, 0)
window.add(vbox)
vbox.show()
#Adding a status bar
self.statusbar = gtk.Statusbar()
vbox.pack_start(self.statusbar, False, False, 0)
#Adding 5 buttons one for each of the activities
button = gtk.Button("Write")
button.connect("clicked", self.clicked_Write)
vbox.pack_end(button, True, True, 2)
button.show()
button2 = gtk.Button("Draw")
button2.connect("clicked", self.clicked_Scrible)
vbox.pack_end(button2, True, True, 2)
button2.show()
button3 = gtk.Button("Final Test")
button3.connect("clicked", self.clicked_Final)
vbox.pack_end(button3, True, True, 2)
button3.show()
button4 = gtk.Button("Helloworld")
button4.connect("clicked", self.clicked_Hello)
vbox.pack_end(button4, True, True, 2)
button4.show()
button5 = gtk.Button("Facebook")
button5.connect("clicked", self.clicked_Facebook)
vbox.pack_end(button5, True, True, 2)
button5.show()
button6 = gtk.Button("SpinButtons")
button6.connect("clicked", self.clicked_Spin)
vbox.pack_end(button6, True, True, 2)
button6.show()
button7 = gtk.Button("Calendar")
button7.connect("clicked", self.clicked_Cal)
vbox.pack_end(button7, True, True, 2)
button7.show()
button8 = gtk.Button("Colour Wheel(click popup)")
button8.connect("clicked", self.clicked_Wheel)
vbox.pack_end(button8, True, True, 2)
button8.show()
button9 = gtk.Button("Choose File")
button9.connect("clicked", self.clicked_File)
vbox.pack_end(button9, True, True, 2)
button9.show()
button10 = gtk.Button("Word Completer")
button10.connect("clicked", self.clicked_Word)
vbox.pack_end(button10, True, True, 2)
button10.show()
window.show_all()
def clicked_Write(self, widget):
# push a new message to the statusbar, using context_id 0
self.statusbar.push(0, "You have oppened Write")
subprocess.Popen(["python", "Helloworld.py"])
def clicked_Scrible(self, widget):
self.statusbar.push(0, "You have opened the Drawind Pad")
subprocess.Popen(["python", "scrible.py"])
def clicked_Final(self, widget):
self.statusbar.push(0, "You have opened the Final Exam")
subprocess.Popen(["python", "Final.py"])
def clicked_Hello(self, widget):
self.statusbar.push(0, "You have opened Helloworld")
subprocess.Popen(["python", "Helloword.py"])
def clicked_Facebook(self, widget):
self.statusbar.push(0, "You have opened Facebook")
subprocess.Popen(["python", "facebookfinal.py"])
def clicked_Spin(self, widget):
self.statusbar.push(0, "You have opened the Spin Buttons App")
subprocess.Popen(["python", "SpinButtons.py"])
def clicked_Cal(self, widget):
self.statusbar.push(0, "You have opened the Calender")
subprocess.Popen(["python", "Calender.py"])
def clicked_Wheel(self, widget):
self.statusbar.push(0, "You have opened the Colour Wheel")
subprocess.Popen(["python", "colour.py"])
def clicked_File(self, widget):
self.statusbar.push(0, "You have opened File Chooser")
subprocess.Popen(["python", "filechooser.py"])
def clicked_Word(self, widget):
self.statusbar.push(0, "You have opened the Word Completer")
subprocess.Popen(["python", "finisher.py"])
def main(self):
gtk.main()
return 0
Example().main()
Here is the code for one of the programmes I open
Colour.py
import pygtk
pygtk.require('2.0')
import gtk
class ColorSelectionExample:
# Color changed handler
def color_changed_cb(self, widget):
# Get drawingarea colormap
colormap = self.drawingarea.get_colormap()
# Get current color
color = self.colorseldlg.colorsel.get_current_color()
# Set window background color
self.drawingarea.modify_bg(gtk.STATE_NORMAL, color)
# Drawingarea event handler
def area_event(self, widget, event):
handled = False
# Check if we've received a button pressed event
if event.type == gtk.gdk.BUTTON_PRESS:
handled = True
# Create color selection dialog
if self.colorseldlg == None:
self.colorseldlg = gtk.ColorSelectionDialog(
"Select background color")
# Get the ColorSelection widget
colorsel = self.colorseldlg.colorsel
colorsel.set_previous_color(self.color)
colorsel.set_current_color(self.color)
colorsel.set_has_palette(True)
# Connect to the "color_changed" signal
colorsel.connect("color_changed", self.color_changed_cb)
# Show the dialog
response = self.colorseldlg.run()
if response -- gtk.RESPONSE_OK:
self.color = colorsel.get_current_color()
else:
self.drawingarea.modify_bg(gtk.STATE_NORMAL, self.color)
self.colorseldlg.hide()
return handled
# Close down and exit handler
def destroy_window(self, widget, event):
gtk.main_quit()
return True
def __init__(self):
self.colorseldlg = None
# Create toplevel window, set title and policies
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_title("Color selection test")
window.set_resizable(True)
# Attach to the "delete" and "destroy" events so we can exit
window.connect("delete_event", self.destroy_window)
# Create drawingarea, set size and catch button events
self.drawingarea = gtk.DrawingArea()
self.color = self.drawingarea.get_colormap().alloc_color(0, 65535, 0)
self.drawingarea.set_size_request(200, 200)
self.drawingarea.set_events(gtk.gdk.BUTTON_PRESS_MASK)
self.drawingarea.connect("event", self.area_event)
# Add drawingarea to window, then show them both
window.add(self.drawingarea)
self.drawingarea.show()
window.show()
def main():
gtk.main()
return 0
if __name__ == "__main__":
ColorSelectionExample()
main()
Put the files in the same directory, then use something like:
from Colour import ColorSelectionExample
then to run it, construct a ColorSelectionExample:
ColorSelectionExample()

Categories

Resources