Visual in Tkinter

Symion <[email protected]>
Newsgroups gmane.comp.python.visualpython.user
Message-ID <[email protected]>
Hi there,

I have recently been testing the Tkinter module with the idea of
building GUI's for controlling things like Visual.

Tkinter makes it very easy to create Lists, Sliders, Buttons, Menus
as well as viewing and editing Text files.

I would like to be able to strip the OS decorator from Visual and
insert the visual.scene into either a Tkinter Canvas or a Tkinter
Frame object.

Alternately, it might be easier to assume Visual is already wrapped
in a Tkinter TopLevel Object and try to insert Tkinter widgets into
the current window surround.

When I chased down this idea and looked at the "ui" module it shed
no light as the instantiation vanished into C!

Is there a way to have them Running and Interacting at the same
time?

Has anyone written code for this?

If this could be achieved it would be very useful!

I note that master.update() might be relevant for Tkinter to
continue operation but how to control Visual?

Any help would be greatly appreciated.

Since I have had problems running Tkinter and Visual together, I
have developed a simple to use method that enables one or the other
to be "in the drivers seat".

It is based on the fact that Visual uses the escape key to end
program execution, so I set Tkinter to act the same.

Now pressing the 'Esc' key will switch between Visual and Tkinter,
no problems!

This means that Tkinter can be used to modify or define Visual
environment or Objects, then press 'Esc' and you are in Visual.

Once in Visual it is possible to modify or define Tkinter
environment or Objects, then press 'Esc' and you are in Tkinter!

Source Code: TkInVisual.py

from Tkinter import *

import vis

from math import (sqrt, pi)

from os import (access as Access, path as Path, F_OK)

class TkInVisual:

"""Tkinter : Visual Interaction.

'esc' key will flip between Visual and Tkinter

Visual Control:

Tkinter Panel:

'f1' = menu on|off

'f2' = canvas on|off

'f3' = button on|off

'enter' = close Tkinter - leave Visual
open

'end' = quit and close Both

"""

def __init__(self):

"""Access multiple lists via Visual/Tkinter"""

self.version="1.0.0"

self.copyright = "Tkinter Method - GNU (c) Symion MMXI"

self.xpos, self.ypos, self.wide, self.high = 8, 8, 400,
300

self.visual = vis.scene

self.visual.visible = False

self.visual.title = "{0} : {1}".format(self.copyright,
self.version)

self.visual.autoscale = False

self.visual.range = 256

self.visual.access = 6 # new vis.scene.variable

#

# For old graphics card users * Time to upgrade? *

#

self.visual.enable_shaders = False

# Pre-set opening list

self.inform = dict()

self.memory = ["Master_methods", "Frame_methods",

"LabelFrame_methods", "Canvas_methods",

"Text_methods", "Entry_methods",

"Listbox_methods", "Scrollbar_methods",

"Label_methods", "Button_methods",

"Menu_methods", "Graphic_methods"]

self.action = ["self.Do_a", "self.Do_b", "self.Do_c",

"self.Do_d", "self.Do_e", "self.Do_f",

"self.Do_g", "self.Do_h", "self.Do_i",

"self.Do_j", "self.Do_k", "self.Do_l"]

def Create_widget(self, title, config):

"""config = [Menu 0|1, Graphic 0|1, Button 0|1|]"""

self.parent = Tk()

self.parent.title(title)

self.parent["borderwidth"] = 4

# Customise Tkinter Panel

self.parent.tk_setPalette(background="#B0B0B0",

activeForeground="#FFFFFF",

selectForeground="#FFFF00",

activeBackground="#FF0000")

# self.parent.geometry("=%dx%d+%d+%d" %(self.wide,

# self.high,

# self.xpos,

# self.ypos))

self.parent.geometry("+%d+%d" % (self.xpos, self.ypos))

self.parent.resizable(width=False, height=False)

self.parent.bind("<Escape>", self.Ok_go)

self.parent.bind("<End>", self.Ok_quit)

base = LabelFrame(self.parent,

fg="#0000FF",

font=("times", 14, "normal"),

bd=5,

text="Tkinter Object Methods")

base.grid()

rows = 0

# config = [Menu 0|1, Graphic 0|1, Button 0|1]

if config[1] > 0:

paper = Canvas(base,

width=self.wide,

height=self.high//3,

bg="#FFFFFF",

relief=RIDGE,

borderwidth=2)

paper.grid(row=rows, column=0, columnspan=2)

rows += 1

if config[0] > 0:

self.menubar = Menu(self.parent)

# create 1st pulldown menu

filemenu = Menu(self.menubar, tearoff=0,

activebackground="#FF0000")

self.menubar.add_cascade(label = " Methods ",
menu=filemenu)

#

for a,b in zip(self.memory[:5], self.action[:5]):

filemenu.add_command(label = a, command=eval(b))

filemenu.add_separator()

filemenu.add_command(label=" Exit : End",
command=self.Ok_quit)

if False:

# create 2nd pulldown

visualmenu = Menu(self.menubar,

tearoff=0,

activebackground="#00FF00")

self.menubar.add_cascade(label=" Visual ",
menu=visualmenu)

visualmenu.add_command(label=" Objects ",
command=self.Test)

visualmenu.add_separator()

visualmenu.add_command(label=" Open ",
command=self.Test)

visualmenu.add_command(label=" Close ",
command=self.Test)

visualmenu.add_separator()

visualmenu.add_command(label=" Edit ",
command=self.Test)

# create 3rd

extramenu = Menu(self.menubar,

tearoff=0,

activebackground="#0000FF")

self.menubar.add_cascade(label=" Extras ",
menu=extramenu)

#

for a,b in zip(self.memory[5:], self.action[5:]):

extramenu.add_command(label = a,
command=eval(b))

#

# display the menu

self.parent["menu"] = self.menubar

self.parent.config(padx=12, pady=12)

self.label = Label(base, font=("times", 14, "normal"))

self.label.grid(row=rows,

column=0,

columnspan=2,

sticky=E+W,

padx=5,

ipadx=5)

rows += 1

# Build a List Table of info.

self.list_table = Listbox(base,

bg="white",

width=50,

borderwidth=2,

font=("times", 12, "normal"),

relief=SUNKEN)

# "A list of Tkinter Object Methods"

self.visual.access = self.visual.access%len(self.memory)

self.Make_list(self.visual.access)

#

self.list_table.grid(row=rows, column=0, columnspan=2,

ipadx=5, ipady=5, sticky=E+W)

self.list_table.bind("<Return>", self.Ach_tung)

self.list_table.bind("<Double-Button-1>",
self.By_pass)

self.scroll_bar = Scrollbar(base,

orient=VERTICAL,

takefocus=FALSE,

highlightthickness=4)

self.scroll_bar["command"] = self.list_table.yview

self.scroll_bar.grid(row=rows, column=1, columnspan=2,
sticky=N+S+E)

self.list_table["yscrollcommand"]= self.scroll_bar.set

self.list_table["activestyle"] = "dotbox"

self.list_table.focus_set()

rows += 1

#

# Button pad

#

if config[2] > 0:

i = 0

for y in range(6):

for x in range(2):

a, b = self.memory[i], eval(self.action[i])

test = Button(base, text=a, command=b)

test.grid(row=rows + y, column=x,
columnspan=1, sticky=E+W)

test.bind("<Return>", b)

i += 1

rows += y + 1

qquit = Button(base, text="Back to Visual",
command=self.Ok_go)

qquit.grid(row=rows, column=0, columnspan=2, sticky=E+W)

qquit.bind("<Return>", self.Ok_go)

def Make_list(self, ndata):

self.visual.access = ndata

self.label["text"] = self.memory[ndata]

self.data = "self.{0}()".format(self.memory[ndata])

self.Build_list(eval(self.data).config().keys())

def Do_remove(self):

n = range(self.list_table.size())

for a in n:

self.list_table.delete(0)

def Build_list(self, table):

self.Do_remove()

for a in table:

self.list_table.insert(END, a)

def Do_a(self, event=None):

self.Make_list(0)

def Do_b(self, event=None):

self.Make_list(1)

def Do_c(self, event=None):

self.Make_list(2)

def Do_d(self, event=None):

self.Make_list(3)

def Do_e(self, event=None):

self.Make_list(4)

def Do_f(self, event=None):

self.Make_list(5)

def Do_g(self, event=None):

self.Make_list(6)

def Do_h(self, event=None):

self.Make_list(7)

def Do_i(self, event=None):

self.Make_list(8)

def Do_j(self, event=None):

self.Make_list(9)

def Do_k(self, event=None):

self.Make_list(10)

def Do_l(self, event=None):

self.Make_list(11)

def Test(self, event=None):

print self.menubar.cget('type')

def Ach_tung(self, event=None):

self.answer = self.list_table.get(ACTIVE)

# Do other things than simply printing it into V-IDLE

# Append to a list or build a dictionary perhaps?

try:

self.inform[self.answer] = (self.visual.access,
self.answer)

a = self.inform.get(self.answer)

# self.inform.append((self.visual.access,
self.answer))

# a = self.inform[-1]

except:

a = None

finally:

if a:

self.De_code(a)

else:

b =
self.memory[self.visual.access].replace("_methods", "")

print "{0}['{1}'] = ".format(b.lower(),
self.answer)

def By_pass(self, event=None):

self.answer = self.list_table.get(ACTIVE)

self.De_code((self.visual.access, self.answer))

def De_code(self, a):

b = self.memory[a[0]]

M = eval("self.{0}()".format(b))

mc = M.cget(a[1])

if mc.__class__.__name__ == "Tcl_Obj":

mc = mc.string

b = b.replace("_methods", "")

print "{0}['{1}'] = {2}".format(b, a[1], repr(mc))

del M

def Ok_go(self, event=None):

self.xpos = self.parent.winfo_x()

self.ypos = self.parent.winfo_y()

self.parent.destroy()

def Ok_quit(self, event=None):

self.Ok_go()

self.acts = False

#

# Make list

#

def Master_methods(self):

return self.parent

def Frame_methods(self):

return Frame(self.parent)

def LabelFrame_methods(self):

return LabelFrame(self.parent)

def Canvas_methods(self):

return Canvas(self.parent)

def Text_methods(self):

return Text(self.parent)

def Entry_methods(self):

return Entry(self.parent)

def Listbox_methods(self):

return Listbox(self.parent)

def Scrollbar_methods(self):

return Scrollbar(self.parent)

def Label_methods(self):

return Label(self.parent)

def Button_methods(self):

return Button(self.parent)

def Menu_methods(self):

return Menu(self.parent)

def Graphic_methods(self):

return self.parent

if __name__ == '__main__':

def Inter_pret():

if len(master.inform) > 0:

master.parent = Tk()

print "\nAccumulated List:"

for c in master.inform.keys():

a = master.inform.get(c)

b = master.memory[a[0]]

M = eval("master.{0}()".format(b))

mc = M.cget(a[1])

if mc.__class__.__name__ == "Tcl_Obj":

mc = mc.string

b = b.replace("_methods", "")

print "{0}.config({1}) = {2}".format(b, a[1],
repr(mc))

del M

else:

print "Returned Empty List."

def Quit():

print
"Zoom({0})".format(vis.mag(master.visual.mouse.camera -
master.visual.center)/sqrt(3.0))

if kb == "\n":

p = dir()

print "Dir() : Length({0})\n".format(len(p))

for j, a in enumerate(p):

print "{0:03.0f} = {1}".format(j, a)

else:

master.visual.visible = False

def Use_visual(x, y, z):

master.visual.visible = True

kb = ""

while 1:

while not master.visual.kb.keys:

if not master.visual.visible and not
master.visual.exit:

master.visual.exit = True

kb = "break"

break

elif master.visual.mouse.events:

mk = master.visual.mouse.getevent()

if mk.release == "left":

if mk.pick:

master.visual.center = mk.pickpos

box.pos = mk.pickpos

else:

master.visual.center =
master.visual.mouse.pickpos

while master.visual.kb.keys:

kb = master.visual.kb.getkey()

print "keyboard event={0}".format(kb)

#

# Function keys f1 to f3 control Tkinter
configuration

#

if kb in ["\n", "end"]:

master.acts = False

break

elif kb in ["f1"]:

x = 1 - x

break

elif kb in ["f2"]:

y = 1 - y

break

elif kb in ["f3"]:

z = 1 - z

break

elif kb == "break":

break

return (kb, x, y, z)

#

# Initialise Tkinter and Setup VPython with visual =
vis.scene

#

master = TkInVisual()

#

# Display some vital information in VIDLE

#

print "{0} : Version({1})\n{2}\n".format(master.copyright,

master.version,

master.__doc__)

#

#

# Arbitrary Visual code ** Replace with Your Visual Code **

#

#

if True:

obj = vis.points(size=1, color=vis.color.red,
shape="square")

w = 30.0

for y in range(50):

for x in range(50):

obj.append((x - w, y - w, 0))

obj.color[-1] = (w / (x + 1), w / (y + 1), w /
(x + y + 1))

box = vis.box(pos=master.visual.center, opacity=0.5,

color=vis.color.red, radius=5)

else:

execfile(Path.join(Path.abspath("."),"Demo.py"))

#

# Tkinter Configuration List for Object.methods = values
Device.

# Initialise Tkinter Default settings to your specification.

#

# x = Menu control ON|OFF

x = 1

# y = Canvas control ON|OFF

y = 0

# z = Buttonpad control ON|OFF

z = 0

#

# config = [Menu 0|1, Graphic 0|1, Button 0|1|2]

#

# Begin

#

master.acts = True

while master.acts:

master.visual.exit = False

master.visual.visible = False

# Build Tkinter Objects

master.Create_widget(master.copyright, config=[x, y, z])

# master.parent.after()

if sys.platform[:3]:

master.parent.iconify()

master.parent.update()

master.parent.deiconify()

master.parent.mainloop()

# Cleanup

del master.parent

if not master.acts:

kb = ""

break

# Visuals turn at the helm

kb, x, y, z = Use_visual(x, y, z)

# React differently if User pressed 'enter' to exit during
Visual phase

Quit()

# Display Results Accumulated during Tkinter Phase

Inter_pret()

Symion

Tuesday, 31 May, 2011

------------------------------------------------------------------------------
Simplify data backup and recovery for your virtual environment with vRanger. 
Installation's a snap, and flexible recovery options mean your data is safe,
secure and there when you need it. Data protection magic?
Nope - It's vRanger. Get your free trial download today. 
http://p.sf.net/sfu/quest-sfdev2dev

_______________________________________________
Visualpython-users mailing list
Visualpython-users-5NWGOfrQmneRv+LV9MX5uipxlwaOVQ5f@public.gmane.org
https://lists.sourceforge.net/lists/listinfo/visualpython-users
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.