PyGTK how to click button and open file in pop-up window - python

I editted the code so that the 3 buttons now show up .Can someone please tell me how to make it so that when I click the button that says Helloworld and application called Helloworld.py will pop-up in another window.Same for the other 2 buttons
!/usr/bin/env python
# menu.py
import pygtk
pygtk.require('2.0')
import gtk
class MenuExample:
def __init__(self):
# create a new window
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_size_request(200, 100)
window.set_title("GTK Menu Test")
window.connect("delete_event", lambda w,e: gtk.main_quit())
# Init the menu-widget, and remember -- never
# show() the menu widget!!
# This is the menu that holds the menu items, the one that
# will pop up when you click on the "Root Menu" in the app
menu = gtk.Menu()
# Next we make a little loop that makes three menu-entries for
# "test-menu". Notice the call to gtk_menu_append. Here we are
# adding a list of menu items to our menu. Normally, we'd also
# catch the "clicked" signal on each of the menu items and setup a
# callback for it, but it's omitted here to save space.
for i in range(3):
# Copy the names to the buf.
buf = "Test-undermenu - %d" % i
# Create a new menu-item with a name...
menu_items = gtk.MenuItem(buf)
# ...and add it to the menu.
menu.append(menu_items)
# Do something interesting when the menuitem is selected
menu_items.connect("activate", self.menuitem_response, buf)
# Show the widget
menu_items.show()
# This is the root menu, and will be the label
# displayed on the menu bar. There won't be a signal handler attached,
# as it only pops up the rest of the menu when pressed.
root_menu = gtk.MenuItem("Root Menu")
root_menu.show()
# Now we specify that we want our newly created "menu" to be the
# menu for the "root menu"
root_menu.set_submenu(menu)
# A vbox to put a menu and a button in:
vbox = gtk.VBox(False, 0)
window.add(vbox)
vbox.show()
# Create a menu-bar to hold the menus and add it to our main window
menu_bar = gtk.MenuBar()
vbox.pack_start(menu_bar, False, False, 2)
menu_bar.show()
# Create a button to which to attach menu as a popup
button = gtk.Button("HelloWorld")
button.connect_object("event", self.button_press, menu)
vbox.pack_end(button, True, True, 2)
button.show()
button2 = gtk.Button("Scrible")
button2.connect_object("event", self.button_press, menu)
vbox.pack_end(button2, True, True, 2)
button2.show()
button3 = gtk.Button("Final")
button3.connect_object("event", self.button_press, menu)
vbox.pack_end(button3, True, True, 2)
button3.show()
# And finally we append the menu-item to the menu-bar -- this is the
# "root" menu-item I have been raving about =)
menu_bar.append (root_menu)
# always display the window as the last step so it all splashes on
# the screen at once.
window.show()
# Respond to a button-press by posting a menu passed in as widget.
#
# Note that the "widget" argument is the menu being posted, NOT
# the button that was pressed.
def button_press(self, widget, event):
if event.type == gtk.gdk.BUTTON_PRESS:
widget.popup(None, None, None, event.button, event.time)
# Tell calling code that we have handled this event the buck
# stops here.
return True
# Tell calling code that we have not handled this event pass it on.
return False
def button2_press(self, widget, event):
if event.type == gtk.gdk.BUTTON2_PRESS:
widget.popup(None, None, None, event.button, event.time)
return True
return False
def button3_press(self, widget, event):
if event.type == gtk.gdk.BUTTON3_PRESS:
widget.popup(None, None, None, event.button, event.time)
return True
return False
# Print a string when a menu item is selected
def menuitem_response(self, widget, string):
print "%s" % string
def main():
gtk.main()
return 0
if __name__ == "__main__":
MenuExample()
main()

You could do something like this. I'm assuming you just want to execute your .py files, e.g. helloworld.py etc. I'm using Popen from subprocess to execute python (not assuming the py files are executable) scripts. Note that I've edited the script to only have one button, this is just to show you the idea.
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(200, 100)
window.set_title("GTK Menu Test")
window.connect("delete_event",
lambda w,e: gtk.main_quit())
vbox = gtk.VBox(False, 0)
window.add(vbox)
vbox.show()
button = gtk.Button("HelloWorld")
button.connect("clicked", self.clicked_helloworld)
vbox.pack_end(button, True, True, 2)
button.show()
window.show_all()
def clicked_helloworld(self, widget):
subprocess.Popen(["python", "helloworld.py"])
def main(self):
gtk.main()
return 0
Example().main()

Related

Python Gtk Notebook making a new tab open from a button

I'm pretty new to OOP and gtk programming, so sorry if the answer my question is really obvious, but I can't find a solution. I am trying to make a browser-like interface using the Gtk notebook. I wrote a method to add tabs, and it seems to work, becasue when I call it in the init, it works, and adds a new tab. Here the method is:
def create_page(self, button):
print("creating a new page")
print(self)
self.newpage = Gtk.Box()
self.newpage.set_border_width(50)
self.newpage.add(Gtk.Label.new("add notes here"))
self.notebook.append_page(self.newpage, Gtk.Label.new("new page"))
The reason the method has to have the button parameter is becasue I want it to be called by a button, and for that to happen, it has to have a button parameter.
When the button calls the parameter, the print statment works, and it prints its self <main.MyWindow object at 0x7efd64e52a80 (main+MyWindow at 0xe60270)>. It prints the exact same output as when I call it from the init.The problem is that it never actually adds the new notebook tab for some reason. Here my full code is:
import gi
# Since a system can have multiple versions
# of GTK + installed, we want to make
# sure that we are importing GTK + 3.
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
class MyWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title ="Stickies Hub")
#self.set_border_width(70)
# Create Notebook
self.notebook = Gtk.Notebook.new()
self.add(self.notebook)
#create buttons
self.new_tab = Gtk.Button(label=("button"))
self.new_tab.connect("clicked", self.create_page)
# Create pages
self.page1 = Gtk.Box()
self.page1.set_border_width(50)
self.page1.add(Gtk.Label.new("Welcome to Geeks for Geeks"))
self.notebook.append_page(self.page1, Gtk.Label.new("Click Here"))
self.page2 = Gtk.Box()
self.page2.set_border_width(50)
self.page2.add(Gtk.Label.new("A computer science portal for geeks"))
self.page2.add(self.new_tab)
self.notebook.append_page(self.page2, Gtk.Label.new("Click Here"))
self.create_page(self.new_tab)
self.create_page(self.new_tab)
def create_page(self, button):
print("creating a new page")
print(self)
self.newpage = Gtk.Box()
self.newpage.set_border_width(50)
self.newpage.add(Gtk.Label.new("new page"))
self.notebook.append_page(self.newpage, Gtk.Label.new("new page"))
win = MyWindow()
win.connect("destroy", Gtk.main_quit)
# Display the window.
win.show_all()
# Start the GTK + processing loop
Gtk.main()
How can I add a new notebook tab from a button?
Thanks so much for help!
As jackw11111 said, the solution was to add self.show_all() at the end of create_page function. Thanks so much!
I made an answer so anyone with this same problem could easily find the answer.
Helloo, Here is my code. I think this will work for you.
from gi.repository import Gdk
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class MyWindow(Gtk.Window):
notebook = Gtk.Notebook()
def __init__(self):
Gtk.Window.__init__(self)
self.set_default_size(750, 500)
self.connect("destroy", Gtk.main_quit)
self.list_view()
def list_view(self):
self.table = Gtk.Table(n_rows=3, n_columns=3, homogeneous=True)
listbox = Gtk.ListBox()
self.add(self.table)
self.add(listbox)
self.two_d_array = {'Hello' : 'Hi', 'Example' : 'Merhaba'}
for i in self.two_d_array.keys():
## label yerine buton oluşturduk
items = Gtk.Button.new_with_label(i)
items.connect("button-press-event",self.button_clicked)
listbox.add(items)
self.table.attach(listbox,0,1,0,3)
self.add(self.notebook)
self.table.attach(self.notebook,1,3,0,3)
self.notebook.show_all()
self.page1 = Gtk.Box()
self.page1.set_border_width(10)
self.page1.add(Gtk.Label(label="Merhaba bu ilk sayfa."))
self.notebook.append_page(self.page1, Gtk.Label(label="Default Page"))
def context_menu(self):
menu = Gtk.Menu()
menu_item = Gtk.MenuItem("New Page")
menu.append(menu_item)
menu_item.connect("activate", self.on_click_popup)
menu.show_all()
return menu
## Buton sağ click ise context menu açtı
def button_clicked(self,listbox_widget,event):
if event.type == Gdk.EventType.BUTTON_PRESS and event.button == 3:
menu = self.context_menu()
## Tıklanan objenin labelini print ediyor
print(listbox_widget.get_label())
self.labelmenu = listbox_widget.get_label()
menu.popup( None, None, None,None, event.button, event.get_time())
return True
def on_pop_menu(self, widget, event):
if event.button == 3:
widget.popup(None, None, None, None, event.button, event.time)
def on_click_popup(self, action):
## Yeni sayfa oluştur
self.new_page = Gtk.Box()
self.new_page.set_border_width(10)
self.new_page.add(Gtk.Label(label=self.two_d_array[self.labelmenu]))
self.notebook.append_page(self.new_page, Gtk.Label(label="New Page"))
self.close_button = Gtk.Button()
self.close_button.set_image(Gtk.Image(Gtk.STOCK_CLOSE,Gtk.IconSize))
self.close_button.connect('clicked')
self.close_button.show()
self.notebook.show_all()
window = MyWindow()
window.show_all()
Gtk.main()

How to toggle fullscreen mode?

I want my application to toggle fullscreen every time you click on the menu item. So if you click once, it becomes fullscreen, if you click again, it becomes normal again. I tried the following but after I clicked it again, it wouldn't switch.
def Fullscreen(self):
self.fullscreen = False
if not self.fullscreen:
self.root.wm_attributes("-fullscreen", True)
else:
self.root.wm_attributes("-fullscreen", False)
You are missing a key part here. Nothing changes full screen back to True.
Here is a simple example of what you could do to toggle full screen.
import tkinter as tk
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
tk.Button(self, text="Toggle Fullscreen", command=self.fullscreen_toggle).pack()
self.fullscreen = False
def fullscreen_toggle(self):
if self.fullscreen == False:
self.wm_attributes("-fullscreen", True)
self.fullscreen = True
else:
self.wm_attributes("-fullscreen", False)
self.fullscreen = False
app = App()
app.mainloop()

Python gtk notebook focus chain

I'm trying to setup a window with a notebook and some pages. Within the pages, there will be some entries (see example code).
I'd like to handle the tab key and arrow keys on my own. I don't want the arrow up key to jump to the page title, I don't want the arrow left / right key to cycle through the pages. I don't want the tab key to cycle through the entries.
Connecting to the key-press signal and checking for tab or arrow keys does not really work.
I tried to change the focus chain, but it still focusses on the page title or cycles through the pages with left / rigth arrow.
Any help / idea is highly appreciated.
#!/usr/bin/env python
import pygtk
import gtk
class NotebookExample:
def __init__(self):
window = gtk.Window(gtk.WINDOW_TOPLEVEL)
window.set_size_request(200,200)
notebook = gtk.Notebook()
notebook.set_tab_pos(gtk.POS_TOP)
notebook.show()
hbox1 = gtk.HBox()
notebook.append_page(hbox1, gtk.Label("Page1"))
hbox2 = gtk.HBox()
notebook.append_page(hbox2, gtk.Label("Page2"))
window.add(notebook)
entry1 = gtk.Entry()
entry2 = gtk.Entry()
entry3 = gtk.Entry()
entry1.set_width_chars(5)
entry2.set_width_chars(5)
entry3.set_width_chars(5)
hbox1.pack_start(entry1, False, False, 10)
hbox1.pack_start(entry2, False, False, 10)
hbox1.pack_start(entry3, False, False, 10)
hbox1.set_focus_chain([entry2, entry3])
window.show_all()
def main():
gtk.main()
return 0
if __name__ == "__main__":
NotebookExample()
main()
Found it.
Listening to the key-press-event and returning "True to stop other handlers from being invoked for the event. False to propagate the event further.
window.connect("key-press-event", self.do_key_press)
def do_key_press(self, widget, event):
if gtk.gdk.keyval_name(event.keyval) == 'Tab':
print "tab"
return True
if gtk.gdk.keyval_name(event.keyval) == 'Left' or gtk.gdk.keyval_name(event.keyval) == 'Right':
print "cursor"
return True
return

Python making gtk.Layout with Scrollbars

How could I have a scrollbar inside a gtk.Layout.
For example, in my code I have:
import pygtk
pygtk.require('2.0')
import gtk
class ScrolledWindowExample:
def __init__(self):
self.window = gtk.Dialog()
self.window.connect("destroy", self.destroy)
self.window.set_size_request(300, 300)
self.scrolled_window = gtk.ScrolledWindow()
self.scrolled_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
self.window.vbox.pack_start(self.scrolled_window, True, True, 0)
self.layout = gtk.Layout()
self.scrolled_window.add(self.layout)
self.current_pos = 0
self.add_buttom()
self.window.show_all()
def add_buttom(self, widget = None):
title = str(self.current_pos)
button = gtk.ToggleButton(title)
button.connect_object("clicked", self.add_buttom, None)
self.layout.put(button, self.current_pos, self.current_pos)
button.show()
self.current_pos += 20
def destroy(self, widget):
gtk.main_quit()
if __name__ == "__main__":
ScrolledWindowExample()
gtk.main()
What I really want is to find some way to make the scroll dynamic. See the example that I put above, when you click any button, another button will be added. But the scrollbar doesn't work.
What can I do to get the scroll bars working?
Does it works if you either use gtk.Window() instead of gtk.Dialog(); or execute self.window.run() after self.window.show_all()?
The difference between Dialog and common Window is that Dialog has its own loop which processes events. As you do not run its run() command, this loop never gets the chance to catch the events, so ScrolledWindow does not receives them, and does not change its size.

Catching a click anywhere inside a gtk.Window

consider the following python code:
import gtk
class MainWindow():
def __init__(self):
self.window = gtk.Window()
self.window.show()
if __name__ == "__main__":
main = MainWindow()
gtk.main()
I'd need to catch clicks anywhere inside this gtk.Window().
I haven't found any suitable event (I also tried button-press-event, but it doesn't work), what am I missing?
Thank you!
You can pack a gtk.EventBox into the window. In general, whenever you have troubles catching events, check if gtk.EventBox solves them.
import gtk
class MainWindow():
def __init__(self):
self.window = gtk.Window()
self.box = gtk.EventBox ()
self.window.add (self.box)
self.box.add (gtk.Label ('some text'))
self.window.show_all()
import sys
self.box.connect ('button-press-event',
lambda widget, event:
sys.stdout.write ('%s // %s\n' % (widget, event)))
if __name__ == "__main__":
main = MainWindow()
gtk.main()
Note, however, that event propagation upwards the widget hierarchy will stop if a widget handles event itself. For instance, a parent of gtk.Button won't receive click events from it.
So i have this DrawingArea in Window. And on click i get the callback
self.drawingarea = gtk.DrawingArea()
self.drawingarea.connect ('button-press-event',self.callback)
self.drawingarea.set_events(gtk.gdk.EXPOSURE_MASK
| gtk.gdk.LEAVE_NOTIFY_MASK
| gtk.gdk.BUTTON_PRESS_MASK
| gtk.gdk.POINTER_MOTION_MASK
| gtk.gdk.POINTER_MOTION_HINT_MASK )
self.window.add(self.drawingarea)
Filter the left or right button:
def callback(self, widget, event):
print "clicking... left or right"
if event.button == 1:
print 'OK - clicked left '
#os.system("""wmctrl -s 0""")
return True

Categories

Resources