Python gtk 模块,main() 实例源码
我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用gtk.main()。
def run(self, graphic):
window = gtk.Window()
self.__window = window
window.set_default_size(200, 200)
vbox = gtk.VBox()
window.add(vbox)
render = GtkGraphicRenderer(graphic)
self.__render = render
vbox.pack_end(render, True, True, 0)
hbox = gtk.HBox()
vbox.pack_start(hbox, False, False, 0)
smaller_zoom = gtk.Button("Zoom Out")
smaller_zoom.connect("clicked", self.__set_smaller_cb)
hbox.pack_start(smaller_zoom)
bigger_zoom = gtk.Button("Zoom In")
bigger_zoom.connect("clicked", self.__set_bigger_cb)
hbox.pack_start(bigger_zoom)
output_png = gtk.Button("Output Png")
output_png.connect("clicked", self.__output_png_cb)
hbox.pack_start(output_png)
window.connect('destroy', gtk.main_quit)
window.show_all()
#gtk.bindings_activate(gtk.main_quit, 'q', 0)
gtk.main()
def main():
(colors, timelines) = read_data(sys.argv[1])
(lower_bound, upper_bound) = timelines.get_bounds()
graphic = GraphicRenderer(lower_bound, upper_bound)
top_legend = TopLegendRenderer()
range_values = timelines.get_all_range_values()
range_colors = []
for range_value in range_values:
range_colors.append(colors.lookup(range_value))
top_legend.set_legends(range_values,
range_colors)
graphic.set_top_legend(top_legend)
data = TimelinesRenderer()
data.set_timelines(timelines, colors)
graphic.set_data(data)
# default range
range_mid = (upper_bound - lower_bound) / 2
range_width = (upper_bound - lower_bound) / 10
range_lo = range_mid - range_width / 2
range_hi = range_mid + range_width / 2
graphic.set_range(range_lo, range_hi)
main_window = MainWindow()
main_window.run(graphic)
def __init__(self,servers):
self.servers = servers;
self.serverInfo = {};
table = gtk.Table(60,50);
self.window = gtk.Window();
inputEntry = self.build_InputEntry();
menuBar = self.build_Menu();
self.noteBook = self.build_Note();
self.messageView = self.build_MessageView();
table.attach(menuBar,0,60,0,10);
table.attach(self.noteBook,0,50,11,50, gtk.EXPAND, gtk.FILL);
table.attach(self.messageView, 51, 60, 11, 50);
table.attach(inputEntry,0,60,51,60)
self.window.set_default_size(1000,700);
self.window.add(table);
self.window.show_all();
self.window.connect("delete_event", self.delete_event)
self.window.connect("destroy", self.destroy)
gtk.main();
def send_keys(self,modifier_byte,keys):
cmd_str=""
cmd_str+=chr(0xA1)
cmd_str+=chr(0x01)
cmd_str+=chr(modifier_byte)
cmd_str+=chr(0x00)
count=0
for key_code in keys:
if(count<6):
cmd_str+=chr(key_code)
count+=1
self.device.send_string(cmd_str);
#main routine
def __init__(self, choices, backend):
self.page_classes = [Welcome, Luks, UsbKey, Unmount, ConfirmUsbKey, \
Format, Gpg, BootScheme, Commit, Finish]
self.builder = gtk.Builder()
self.builder.add_from_file(os.path.join(sys.prefix, "share/lfde-installer/gui/gtk/main.glade"))
self.builder.connect_signals({"on_win_main_destroy" : self.gui_quit,
"on_btn_forward_clicked" : self.gui_forward,
"on_btn_back_clicked" : self.gui_back,
"on_btn_quit_clicked" : self.gui_quit })
# allow our threads to work normally
gtk.gdk.threads_init()
self.win_main = self.builder.get_object("win_main")
self.lbl_step_title = self.builder.get_object("lbl_step_title")
self.builder.add_from_file(os.path.join(sys.prefix, "share/lfde-installer/gui/gtk/entropy.glade"))
self.win_entropy = self.builder.get_object("win_entropy")
self.lbl_step = self.builder.get_object("lbl_step")
self.btn_forward = self.builder.get_object("btn_forward")
GenericFrontend.__init__(self, choices, backend)
def on_button1_clicked(self, *args):
global STOP_SIGNAL
button = self.builder.get_object("button1")
spinner = self.builder.get_object("spinner1")
checkbox1 = self.builder.get_object("checkbutton1")
if button.get_label() == "Start":
STOP_SIGNAL = False
button.set_label("Stop")
checkbox1.set_sensitive(False)
spinner.set_visible(True)
spinner.start()
self.t = multiprocessing.Process(target=main, args=())
self.t.start()
else:
STOP_SIGNAL = True
button.set_label("Start")
checkbox1.set_sensitive(True)
spinner.set_visible(False)
spinner.stop()
self.t.terminate()
def Main():
train=False
print 'training started'
if train:
v=Video()
n=NormalizedRGB()
for i in range(100):
frm=v.outFrame()
n.getRGB(frm)
norm=n.normalized()
plain=v.imagePlanes(norm)
sample_bg(plain[1])
print 'training ends...'
del v
m=MainUI()
gtk.main()
def lienInAmelia():
import gtk
import webkit
import gobject
gobject.threads_init()
window = gtk.Window()
window.set_default_size(1100, 680)
window.connect("destroy", lambda a: gtk.main_quit())
browser = webkit.WebView()
browser.open("http://alfred-ia.org/essaye-moi/")
window.add(browser)
window.show_all()
gtk.main()
def thread_gtk(self):
self.thrd = Thread(target=gtk.main, name = "GTK thread")
self.thrd.daemon = True
self.thrd.start()
def main(args=None):
if args is None:
args = sys.argv[1:]
if len(args) < 1:
print("usage: pyftinspect font...", file=sys.stderr)
return 1
for arg in args:
Inspect(arg)
gtk.main()
def start(self):
gimp.main(self.init, self.quit, self.query, self._run)
def main():
if len(args) <= 0:
open_file()
else:
play_args = pre_play(args[0])
play(play_args)
gtk.main()
def _toggle_interface(self, show):
"""Helper function to toggle the main game interface on/off when game starts/ends."""
self.bid_text.set_sensitive(show)
self.button_fold.set_sensitive(show)
self.button_check.set_sensitive(show)
self.button_call.set_sensitive(show)
self.button_raise_bid.set_sensitive(show)
if not show:
self.button_shuffle.show()
def __init__(self, useGtk=True):
self.context = gobject.main_context_default()
self.loop = gobject.MainLoop()
posixbase.PosixReactorBase.__init__(self)
# pre 2.3.91 the glib iteration and mainloop functions didn't release
# global interpreter lock, thus breaking thread and signal support.
if (hasattr(gobject, "pygtk_version") and gobject.pygtk_version >= (2, 3, 91)
and not useGtk):
self.__pending = self.context.pending
self.__iteration = self.context.iteration
self.__crash = self.loop.quit
self.__run = self.loop.run
else:
import gtk
self.__pending = gtk.events_pending
self.__iteration = gtk.main_iteration
self.__crash = _our_mainquit
self.__run = gtk.main
# The input_add function in pygtk1 checks for objects with a
# 'fileno' method and, if present, uses the result of that method
# as the input source. The pygtk2 input_add does not do this. The
# function below replicates the pygtk1 functionality.
# In addition, pygtk maps gtk.input_add to _gobject.io_add_watch, and
# g_io_add_watch() takes different condition bitfields than
# gtk_input_add(). We use g_io_add_watch() here in case pygtk fixes this
# bug.
def _doReadOrWrite(self, source, condition, faildict={
error.ConnectionDone: failure.Failure(error.ConnectionDone()),
error.ConnectionLost: failure.Failure(error.ConnectionLost()),
}):
why = None
didRead = None
if condition & POLL_DISCONNECTED and \
not (condition & gobject.IO_IN):
why = main.CONNECTION_LOST
else:
try:
if condition & gobject.IO_IN:
why = source.doRead()
didRead = source.doRead
if not why and condition & gobject.IO_OUT:
# if doRead caused connectionLost, don't call doWrite
# if doRead is doWrite, don't call it again.
if not source.disconnected and source.doWrite != didRead:
why = source.doWrite()
didRead = source.doWrite # if failed it was in write
except:
why = sys.exc_info()[1]
log.msg('Error In %s' % source)
log.deferr()
if why:
self._disconnectSelectable(source, why, didRead == source.doRead)
def run(self, installSignalHandlers=1):
import gtk
self.startRunning(installSignalHandlers=installSignalHandlers)
self.simulate()
# mainloop is deprecated in newer versions
if hasattr(gtk, 'main'):
gtk.main()
else:
gtk.mainloop()
def install(useGtk=True):
"""Configure the twisted mainloop to be run inside the gtk mainloop.
@param useGtk: should glib rather than GTK+ event loop be
used (this will be slightly faster but does not support GUI).
"""
reactor = Gtk2Reactor(useGtk)
from twisted.internet.main import installReactor
installReactor(reactor)
return reactor
def portableInstall(useGtk=True):
"""Configure the twisted mainloop to be run inside the gtk mainloop.
"""
reactor = PortableGtkReactor()
from twisted.internet.main import installReactor
installReactor(reactor)
return reactor
def run(self, installSignalHandlers=1):
self.startRunning(installSignalHandlers=installSignalHandlers)
self.simulate()
gtk.main()
def install():
"""Configure the twisted mainloop to be run inside the gtk mainloop.
"""
reactor = GladeReactor()
from twisted.internet.main import installReactor
installReactor(reactor)
return reactor
def run(self):
while not self.quit:
#print "sim: Wait for go"
self.go.wait() # wait until the main (view) thread gives us the go signal
self.go.clear()
if self.quit:
break
#self.go.clear()
#print "sim: Acquire lock"
self.lock.acquire()
try:
if 0:
if ns3.core.Simulator.IsFinished():
self.viz.play_button.set_sensitive(False)
break
#print "sim: Current time is %f; Run until: %f" % (ns3.Simulator.Now ().GetSeconds (), self.target_time)
#if ns3.Simulator.Now ().GetSeconds () > self.target_time:
# print "skipping, model is ahead of view!"
self.sim_helper.SimulatorRunUntil(ns.core.Seconds(self.target_time))
#print "sim: Run until ended at current time: ", ns3.Simulator.Now ().GetSeconds ()
self.pause_messages.extend(self.sim_helper.GetPauseMessages())
gobject.idle_add(self.viz.update_model, priority=PRIORITY_UPDATE_MODEL)
#print "sim: Run until: ", self.target_time, ": finished."
finally:
self.lock.release()
#print "sim: Release lock, loop."
# enumeration
def start(self):
self.scan_topology()
self.window.connect("delete-event", self._quit)
#self._start_update_timer()
gobject.timeout_add(200, self.autoscale_view)
self.simulation.start()
try:
__IPYTHON__
except NameError:
pass
else:
self._monkey_patch_ipython()
gtk.main()
def _test():
from enchant.checker import SpellChecker
text = "This is sme text with a fw speling errors in it. Here are a fw more to tst it ut."
printf(["BEFORE:", text])
chk_dlg = GtkSpellCheckerDialog()
chk_dlg.show()
chk_dlg.connect('delete_event', gtk.main_quit)
chkr = SpellChecker("en_US",text)
chk_dlg.setSpellChecker(chkr)
chk_dlg.updateUI()
gtk.main()
def serve_forever(self):
gtk.gdk.threads_enter()
gtk.main()
gtk.gdk.threads_leave()
def serve_forever(self):
gtk.gdk.threads_enter()
gtk.main()
gtk.gdk.threads_leave()
def inputhook_gtk():
gobject.io_add_watch(sys.stdin, gobject.IO_IN, _main_quit)
gtk.main()
return 0
def inputhook(context):
"""
When the eventloop of prompt-toolkit is idle, call this inputhook.
This will run the GTK main loop until the file descriptor
`context.fileno()` becomes ready.
:param context: An `InputHookContext` instance.
"""
def _main_quit(*a, **kw):
gtk.main_quit()
return False
gobject.io_add_watch(context.fileno(), gobject.IO_IN, _main_quit)
gtk.main()
def main(argv):
global commands
# now we need to find out if one of the commands are in the
# argv list, and if so split the list at the point to
# separate the argv list at that point
cut = None
for i in range(len(argv)):
if argv[i] in commands or argv[i] in aliases:
cut = i
break
if cut == None:
usage(argv)
os._exit(0)
return
# lol no options for now
globaloptionparser = optparse.OptionParser()
globaloptionparser.parse_args(argv[0:i])
# now dispatch and run
result = None
if argv[i] in commands:
result = commands[argv[i]](argv[i+1:])
elif argv[i] in aliases:
result = aliases[argv[i]](argv[i+1:])
# flush, in case output is rerouted to a file.
console_flush()
# done
return result
def main(self):
thread = Thread(target=uBitPoller)
thread.daemon = True
thread.start()
thread = Thread(target=pipePoller, args=(self,))
thread.daemon = True
thread.start()
thread = Thread(target=updateTitle)
thread.daemon = True
thread.start()
gtk.main()
def copy_url(url):
"""Copy the url into the clipboard."""
# try windows first
try:
import win32clipboard
except ImportError:
# then give pbcopy a try. do that before gtk because
# gtk might be installed on os x but nobody is interested
# in the X11 clipboard there.
from subprocess import Popen, PIPE
try:
client = Popen(['pbcopy'], stdin=PIPE)
except OSError:
try:
import pygtk
pygtk.require('2.0')
import gtk
import gobject
except ImportError:
return
gtk.clipboard_get(gtk.gdk.SELECTION_CLIPBOARD).set_text(url)
gobject.idle_add(gtk.main_quit)
gtk.main()
else:
client.stdin.write(url)
client.stdin.close()
client.wait()
else:
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(url)
win32clipboard.CloseClipboard()
def main(self, task=None,checkpoint=None):
self.zarj_comm.start()
self.window.show_all()
self.idle_id = gobject.idle_add(self.gtk_idle_cb)
if task is not None and checkpoint is not None:
msg = ZarjStartCommand(task, checkpoint, True)
self.zarj_comm.push_message(msg)
gtk.main()
self.zarj_comm.stop()
def draw_lidar(self):
if self.lidar_msg is not None:
pixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, 512, 20)
a = pixbuf.get_pixels_array()
camera_increment = (2 * 1.3962) / 512
offset = (len(self.lidar_msg.ranges) - (2 * 512)) / 2
scale = 255.0 / (self.lidar_msg.range_max - self.lidar_msg.range_min)
for x in range(512):
angle = -1.3962 + (camera_increment * x)
distance = self.lidar_distance_for_angle(angle)
self.lidar_depth[x] = round(distance, 2)
if distance <= self.lidar_msg.range_min:
scaled = 0
elif distance >= self.lidar_msg.range_max:
scaled = 255
else:
scaled = distance * scale
color = [ 0, 255 - int(scaled), 0 ]
for y in range(20):
a[y, x] = color
if round(math.degrees(angle), 0) % 30 == 0:
a[0, x] = [255, 0, 0]
a[19, x] = [255, 0, 0]
if angle == 0.0:
a[0, x] = [255, 0, 0]
a[1, x] = [255, 0, 0]
a[18, x] = [255, 0, 0]
a[19, x] = [255, 0, 0]
pixmap, mask = pixbuf.render_pixmap_and_mask()
self.lidar.set_from_pixmap(pixmap, mask)
# Ideally, we process in the main thread context, hopefully
# preventing bugs...
def run( Widget, w, h, speed ):
window = gtk.Window( )
window.connect( "delete-event", gtk.main_quit )
widget = Widget( w, h, speed )
widget.show( )
window.add( widget )
window.present( )
gtk.main( )
def run(Widget):
window = gtk.Window()
window.connect("delete-event", gtk.main_quit)
widget = Widget()
widget.show()
window.add(widget)
window.present()
gtk.main()
def show(self):
"""Opens a GTK window and puts the heatmap in it. Intelligent enough to work with the GUI as well."""
window_only = 1 #What needs to be destroyed when the window is destroyed?
if HMAP_ENABLED and DISPLAY_ENABLED:
def destroy():
if window_only:
window.destroy()
else:
gtk.main_quit()
gtk.gdk.threads_enter()
window = gtk.Window()
window.set_title("Showing heatmap...")
window.set_border_width(10)
window.set_resizable(False)
window.connect("delete_event", lambda w, e: destroy())
backbone = gtk.HBox(True)
image = gtk.Image()
image.set_from_pixbuf(self._image_to_pixbuf(self.im))
backbone.pack_start(image)
window.add(backbone)
window.show_all()
gtk.gdk.threads_leave()
if gtk.main_level() == 0:
window_only = 0
gtk.main()
else:
raise "HmapError", "Error loading modules or unable to display"
def __init__(self, useGtk=True):
self.context = gobject.main_context_default()
self.loop = gobject.MainLoop()
posixbase.PosixReactorBase.__init__(self)
# pre 2.3.91 the glib iteration and mainloop functions didn't release
# global interpreter lock, thus breaking thread and signal support.
if (hasattr(gobject, "pygtk_version") and gobject.pygtk_version >= (2, 3, 91)
and not useGtk):
self.__pending = self.context.pending
self.__iteration = self.context.iteration
self.__crash = self.loop.quit
self.__run = self.loop.run
else:
import gtk
self.__pending = gtk.events_pending
self.__iteration = gtk.main_iteration
self.__crash = _our_mainquit
self.__run = gtk.main
# The input_add function in pygtk1 checks for objects with a
# 'fileno' method and, if present, uses the result of that method
# as the input source. The pygtk2 input_add does not do this. The
# function below replicates the pygtk1 functionality.
# In addition, pygtk maps gtk.input_add to _gobject.io_add_watch, and
# g_io_add_watch() takes different condition bitfields than
# gtk_input_add(). We use g_io_add_watch() here in case pygtk fixes this
# bug.
def _doReadOrWrite(self, source, condition, faildict={
error.ConnectionDone: failure.Failure(error.ConnectionDone()),
error.ConnectionLost: failure.Failure(error.ConnectionLost()),
}):
why = None
didRead = None
if condition & POLL_DISCONNECTED and \
not (condition & gobject.IO_IN):
why = main.CONNECTION_LOST
else:
try:
if condition & gobject.IO_IN:
why = source.doRead()
didRead = source.doRead
if not why and condition & gobject.IO_OUT:
# if doRead caused connectionLost, don't call doWrite
# if doRead is doWrite, don't call it again.
if not source.disconnected and source.doWrite != didRead:
why = source.doWrite()
didRead = source.doWrite # if failed it was in write
except:
why = sys.exc_info()[1]
log.msg('Error In %s' % source)
log.deferr()
if why:
self._disconnectSelectable(source, why, didRead == source.doRead)
def run(self, installSignalHandlers=1):
import gtk
self.startRunning(installSignalHandlers=installSignalHandlers)
self.simulate()
# mainloop is deprecated in newer versions
if hasattr(gtk, 'main'):
gtk.main()
else:
gtk.mainloop()
def install(useGtk=True):
"""Configure the twisted mainloop to be run inside the gtk mainloop.
@param useGtk: should glib rather than GTK+ event loop be
used (this will be slightly faster but does not support GUI).
"""
reactor = Gtk2Reactor(useGtk)
from twisted.internet.main import installReactor
installReactor(reactor)
return reactor
def portableInstall(useGtk=True):
"""Configure the twisted mainloop to be run inside the gtk mainloop.
"""
reactor = PortableGtkReactor()
from twisted.internet.main import installReactor
installReactor(reactor)
return reactor
def run(self, installSignalHandlers=1):
self.startRunning(installSignalHandlers=installSignalHandlers)
self.simulate()
gtk.main()
def install():
"""Configure the twisted mainloop to be run inside the gtk mainloop.
"""
reactor = GladeReactor()
from twisted.internet.main import installReactor
installReactor(reactor)
return reactor
def main():
#
# In order to uniquely identify the service, pass in an
# alias name and socket id on the command line
global g_service_alias
global g_socket_id
if len(sys.argv) == 3:
g_service_alias = sys.argv[1]
g_socket_id = int(sys.argv[2])
elif len(sys.argv) > 2:
print "Usage: lcd_service.py (service_alias_name socket_id)"
sys.exit(2)
else:
# defaults
g_service_alias = "LCD1"
g_socket_id = 18861
print "Using service alias:", g_service_alias, " and socket id", g_socket_id
# Initialize threads
gtk.threads_init()
start_new_display()
start_new_service()
# gtk multithreaded stuff
gtk.threads_enter()
gtk.main()
gtk.threads_leave()