Update User interface when a button is pressed Tkinter - python

So basically i want the user interface to be updated when a user presses the start button, however when i call the maininit function it returns an error saying that root is not defined, is there any way i can get around this?
from PIL import Image, ImageTk
from Tkinter import Tk, Label, BOTH,W, N, E, S, Entry, Text, INSERT, Toplevel
from ttk import Frame, Style, Button, Label
import Tkinter
import Callingwordlist
class MainGameUI(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Type!")
self.pack(fill=BOTH, expand=1)
style = Style()
style.configure("TFrame", background="black")
Type = Image.open("Type!.png")
Typet = ImageTk.PhotoImage(Type)
label3 = Label(self, image=Typet)
label3.image = Typet
label3.place(x=0, y=0)
self.pack(fill=BOTH, expand=1)
MenuButton = Button(self, text="Main Menu")
MenuButton.pack()
MenuButton.place(x=560,y=20,height = 80,width = 100)
QuitButton = Button(self,text="Quit",command=self.parent.destroy)
QuitButton.pack()
QuitButton.place(x=680,y=20,height = 80,width = 100)
StartButton = Button(self, text="Start",command=maininit)
StartButton.pack()
StartButton.place(x=440,y=20,height=80,width=100)
def maininit():
entry1 = Entry(root,font =("Courier",38), width = 22)
entry1.pack(ipady=10)
entry1.config(bg="#CEF6F5")
entry1.place(x=90,y=200)
entry2 = Entry(root,font =("Courier",38), width = 22)
entry2.pack(ipady=10)
entry2.config(bg="#CEF6F5")
entry2.place(x=90,y=350)
text1 = Text(root,width=23,height=1,font=("Courier",38))
text1.pack()
text1.config(bg="black",fg="white",bd=0)
text1.place(x=90,y=150)
text1.insert(INSERT,"Hello")
text2 = Text(root,width=23,height=1,font=("Courier",38))
text2.pack()
text2.config(bg="black",fg="white",bd=0)
text2.place(x=90,y=300)
text2.insert(INSERT,"Test")
dtext = Text(root,font=("Courier",28),width=10,height=1)
dtext.pack()
dtext.config(bg="black",fg="white",bd=0)
dtext.insert(INSERT,"Difficulty")
dtext.place(x=90,y=500)
atext = Text(root,font=("Courier",28),width=8,height=1)
atext.pack()
atext.config(bg="black",fg="white",bd=0)
atext.insert(INSERT,"Accuracy")
atext.place(x=595,y=500)
dentry = Text(root,font=("Courier",28),width=1,height=1)
dentry.pack()
dentry.config(bg="white",bd=0)
dentry.place(x=180,y=550)
dentry.insert(INSERT,"Test")
def main():
root = Tk()
root.geometry("860x640+300+300")
app = MainGameUI(root)
root.mainloop()
if __name__ == '__main__':
main()

In your application, root is a locally defined variable confined to main(). You need to somehow pass root as an argument to maininit. Here is one way to do this:
First, change maininit() so that it accepts a parameter root:
def maininit(root):
...
Now, change the callback on StartButton so it passes maininit() the root object:
class MainGameUI(Frame):
...
def initUI(self):
...
StartButton = Button(self, text="Start",command=lambda: maininit(self.parent))
...

You are defining root inside a function, whose calling namespace is not available to the maininit() function. If you omit the definition of main() and instead write
if __name__ == "__main__":
root = Tk()
root.geometry("860x640+300+300")
app = MainGameUI(root)
root.mainloop()
root will then be defined in the global module namespace, where it IS available to the code in the function.

Related

Pararell instance of tkinter application window python

I want to create some simple tkinter python app (like StickyNotes on Windows), i have create the class mainApplication and i do not know how to by just simply triggering the button create another instance of this class which will be displayed pararell to other window (or even multiple windows). I know how to assigned function to pushButton, and other simple stuff but the problem is with this pararell window displaying. Thanks in advance for help.
class mainApplication(Frame):
_ids = count(0)
def __init__(self, parent):
""" """
self.id = next(self._ids)
Frame.__init__(self, parent)
self.parent = parent
self.parent.minsize(width=200,height=100)
self.parent.geometry(('%dx%d+%d+%d' % (200, 100, 1700, 0+self.id*100)))
self.initUI()
def initUI(self):
""" """
self.parent.title("a2l")
self.pack(fill=BOTH, expand=True)
style = Style()
style.configure("TFrame", background="#333")
frame1 = Frame(self, style="TFrame")
frame1.pack(fill=X)
self.lbl0 = Label(frame1, text="api", width=7, background="#333", foreground = "red")
self.lbl0.pack(side=TOP, padx=5, pady=5)
self.closeButton = Button(self, text="new", command = self.createNewInstance)
self.closeButton.pack(side=RIGHT, padx=5, pady=5)
#=======================================================================
# self.generateButton = Button(self, text="GENERATE", command = self.)
# self.generateButton.pack(side=RIGHT, padx=5, pady=5)
#=======================================================================
def createNewInstance(self):
y = mainApplication()
return y
if __name__ == "__main__":
root = Tk()
x = mainApplication(root).pack(side="top", expand=False)
Tk().mainloop()
You shouldn't create more than one Tk() window in one application with tkinter. Instead tkinter provides a widget called Toplevel which can be useful for this kind of thing.
It creates another window which can exist along side the Tk() window and alongside other Toplevel widgets.
You could use this to create a series of persistent windows with whatever text or widgets you wanted on them at any kind of trigger including a Button.
See my example below for a demonstration:
from tkinter import *
class App:
def __init__(self, root):
self.root = root
self.top = [] #list to contain the Toplevel widgets
self.entry = Entry(self.root)
self.button = Button(self.root, text="Create window", command=self.command)
self.entry.pack()
self.button.pack()
def command(self): #called when button is pressed
self.top.append(Toplevel(self.root)) #adds new Toplevel to the list
Label(self.top[len(self.top)-1], text=self.entry.get()).pack() #Adds label equal to the entry widget to the new toplevel
root = Tk()
App(root)
root.mainloop()

Python tkinter checkbutton value not accessible

I want to build a little GUI application in Python. The goal is to have a main window calling several other windows. In one of these called windows I have a checkbutton. My problem is that I cannot read the value of this checkbutton, whereas I can read the value of an Entry widget. What am I doing wrong?
from tkinter import *
import tkinter as tk
class mainwindow():
def __init__(self, master):
self.master = master
menubalk = Menu(self.master)
menubalk.add_command(label="New window", command=self.openNewwindow)
self.master.config(menu=menubalk)
def openNewwindow(self):
window = newwindow()
window.mainloop()
class newwindow(Tk):
def __init__(self):
Tk.__init__(self)
self.var = BooleanVar()
self.checkbutton = Checkbutton(self, text="Check", variable=self.var)
self.checkbutton.grid(column=0, row=0)
self.var2 = StringVar()
self.entry = Entry(self, textvariable=self.var2)
self.entry.grid(column=2,row=0)
self.button2 = Button(self,text=u"Show", command=self.showValues).grid(column=1, row=0)
def showValues(self):
print('Value checkbutton:', self.var.get(), ';', 'Value entryfield: ', self.entry.get())
def main():
root = Tk()
window = mainwindow(root)
root.mainloop()
if __name__ == '__main__':
main()
You are making multiple, separate Tkinter applications in your program. Do not do that. To create new windows, use the Toplevel widget.
from tkinter import *
class mainwindow():
def __init__(self, master):
self.master = master
menubalk = Menu(self.master)
menubalk.add_command(label="New window", command=self.openNewwindow)
self.master.config(menu=menubalk)
def openNewwindow(self):
def showValues(var, entry):
print('Value checkbutton:', var.get(), ';', 'Value entryfield: ', entry.get())
window = Toplevel(self.master)
var = BooleanVar()
checkbutton = Checkbutton(window, text="Check", variable=var)
checkbutton.grid(column=0, row=0)
var2 = StringVar()
entry = Entry(window, textvariable=var2)
entry.grid(column=2,row=0)
button2 = Button(window,text=u"Show", command=lambda: showValues(var, entry))
button2.grid(column=1, row=0)
def main():
root = Tk()
window = mainwindow(root)
root.mainloop()
if __name__ == '__main__':
main()
Tkinter's variable objects (IntVar, StringVar, etc.) must take argument "master" as their firs parameter. i.e. replace
self.var=StringVar()
With
self.var=StringVar(self)
Or
self.var=StringVar(master=self)

get variable in tkinter frame class and send it to another python script

i need to send one variable from one tkinter script to other python script.
my code is like this.
import os
import sys
from Tkinter import *
import Tkinter as tk
class SeaofBTCapp(tk.Tk):
def __init__(self,*args,**kwargs):
## class parent and parameter
def show_frame(self, cont):
frame = self.frames[cont]
frame.tkraise()
class PageDigital(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self,parent)
entry = Entry(self, width=13, font=("Helvetica", 20))
entry.place(x=50, y=300)
def OK():
os.system('pri.py')
button21 = tk.Button(self, text="OK", font=("Helvetica", 15), width=8,command=OK)
button21.place(x=300, y=300)
write1=entry1["text"]
import pri
app = SeaofBTCapp()
app.mainloop()
i need to send string inside entry to pri.py and print it
pri.py script is like this
from __main__ import *
print write1
thanks
Try making the OK function pass entry.get() to the pri.py script, this should pass the value of the StringVar to your script.
If you need to close your frame before passing/printing it, turn the entry into a member variable (self.entry = Entry(..)) and access it outside of the class/functions with app.entry.get().
EDIT 06/27: New code example. Here you can see how I'm able to use the class structure to access the variable obtained from the first Entry field and display it in the Label of the Toplevel. I hope this is able to help as I'm not 100% sure on what you're trying to do.
from tkinter import *
class Window():
def __init__(self, root):
self.f = Frame(root)
self.f.pack()
self.e = Entry(self.f, width = 20)
self.e.pack(side = LEFT)
self.b = Button(self.f, width = 15, text = "OK", command = lambda: self.OK(root))
self.b.pack(side = RIGHT)
def OK(self, root):
print ("Accessing entry inside class: %s" %self.e.get()) #Could pass to pri.py here
self.word = self.e.get()
new = self.newWindow()
root.wait_window(new)
root.destroy()
def newWindow(self):
def done(newWindow):
newWindow.destroy()
newWindow = Toplevel()
newWindow.tkraise() # <- Personally never needed this, but it's in
l = Label(newWindow, text = "Here is the variable in a top window: %s" %self.word) #Using the variable in another window
l.pack(side = LEFT)
b = Button(newWindow, text = "Done", command = lambda: done(newWindow))
b.pack(side = RIGHT)
return newWindow
root = Tk()
w = Window(root)
w.f.mainloop()
print ("Accessing entry outside class: %s" %w.word) #Or here

Python: Tkinter OK button callback function

I'm working on my very first Python GUI and I'm trying to modify this tkinter example, but I simply cannot figure out how to write a callback function for the OK button that will pass on the entered value to the main program.
#!/usr/bin/python
# -*- coding: utf-8 -*-
from Tkinter import Tk, BOTH, StringVar, IntVar
from ttk import Frame, Button, Style, Label, Entry
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Get Value")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
valueLabel = Label(self, text="Value: ")
valueLabel.place(x=10, y=10)
value=StringVar(None)
value.set("this is the default value")
valueEntry=Entry(self, textvariable=value)
valueEntry.place(x=70, y=10)
quitButton = Button(self, text="Quit", command=self.quit)
quitButton.place(x=10, y=50)
okButton = Button(self, text="OK", command=self.quit)
okButton.place(x=120, y=50)
def main():
root = Tk()
root.geometry("220x100+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
I've read a gazillion of tutorials, but none of them explains this clearly. Theoretically, I should be able to get the selected value with value.get(), but I keep getting error messages no matter where I put it. Also, AFAIK, I should be able to define a default value with value.set(), but this doesn't seem to have an effect, since the text box is empty when I run the program.
What is the easiest way to pass on values to the main python program after root.mainloop() terminates? (The actual dialog box contains several entry boxes for entering string and integer values.)
I.e. I want to be able to use something like:
root = Tk()
root.geometry("220x100+300+300")
app = Example(root)
root.mainloop()
print value
print value2
print value3
How do I define default values for entry boxes?
Change every occurrence of the value variable with self.value. This should fix it and the default value will be displayed.
UPDATE
from Tkinter import Tk, BOTH, StringVar, IntVar
from ttk import Frame, Button, Style, Label, Entry
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def showMe(self):
print(self.value.get())
def initUI(self):
self.parent.title("Get Value")
self.style = Style()
self.style.theme_use("default")
self.pack(fill=BOTH, expand=1)
valueLabel = Label(self, text="Value: ")
valueLabel.place(x=10, y=10)
self.value=StringVar(None)
self.value.set("this is the default value")
valueEntry=Entry(self, textvariable=self.value)
valueEntry.place(x=70, y=10)
quitButton = Button(self, text="Quit", command=self.quit)
quitButton.place(x=10, y=50)
okButton = Button(self, text="OK", command=self.showMe)
okButton.place(x=120, y=50)
def main():
root = Tk()
root.geometry("220x100+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
Both your quitButton and okButton call the self.quit functions. So no mater what value you enter when you press the OK button you are calling the quit function which has its own problems as well outside the scope of your question.
Try to define value as self.value and make the okButton call a function that does: print self.value.get().

Get value from Entry of Tkinter

Similar questions have been asked, but none of them address the particular way my script is constructed:
from Tkinter import *
from ttk import *
class Gui(Frame):
def __init__(self, parent):
Frame.__init__(self, parent) #Gui inherits from built in Frame Class
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Shoes Ware")
self.pack(fill=BOTH, expand=1)
run_val = Entry(self)
run_val["width"] = 5
run_val.place(x=80, y=40)
quit_B = Button(self, text="Submit", command=self.submit)
quit_B.place(x=130, y=170)
def submit(self):
value = run_val.get()
print value
self.quit()
def main():
root = Tk()
root.geometry("300x200+50+50")
app = Gui(root)
root.mainloop()
if __name__ == '__main__':
main()
I get "NameError: global name 'run_val' is not defined" when I hit the submit button. What am I doing wrong here. Right now the print statement is just to check my work. Later on, I'll be using that value in a program.
You are not storing the reference to the Entry widget in initUI.
def initUI(self):
# ...
self.run_val = Entry(self)
self.run_val["width"] = 5
self.run_val.place(x=80, y=40)
Then you can retrieve the value of self.run_val.get() without any problem.

Categories

Resources