I am looking for a way to change the content of the window based on what option you select in the OptionMenu. It should have 3 different options, namely "Introduction", "Encrypt" and "Decrypt". I've the code to create an OptionMenu but now I wanna know how can I modify them to show a different page, depending on the one who is selected. Could someone help me with that? I am using python 3
so for example:
from tkinter import *
OptionList = [
"Einführung",
"Verschlüsseln",
"Entschlüsseln"
]
window = Tk()
window.geometry('200x200')
variable = StringVar(window)
variable.set(OptionList[0])
opt = OptionMenu(window, variable, *OptionList)
opt.config(width=90, font=('Calbri', 12))
opt.pack(side="top")
window.mainloop()
This will produce a window with a OptionMenu with the three options I wrote above (just in German) and now I'd like to change the page depending on the current chosen option of the OptionMenu
Thanks guys!
This is now the forth edit or something, but thats the final solution i've come up with.
#coding=utf-
import tkinter as tk
from tkinter import *
window = Tk()
window.geometry('200x200')
OptionList = ["Einführung", "Verschlüsseln", "Entschlüsseln"]
class App:
def __init__(self, master):
self.choice_var = tk.StringVar()
self.choice_var.set(OptionList[0])
opt = OptionMenu(window, self.choice_var, *OptionList, command=self.switch)
opt.config(width=90, font=('Calbri', 12))
opt.pack(side="top")
self.random_label1 = tk.Label(window, text="Welcome content here")
self.random_label2 = tk.Label(window, text="Encrypt content here")
self.random_label3 = tk.Label(window, text="Decrypt content here")
self.random_label1.pack()
self.random_label2.pack()
self.random_label3.pack()
self.label_info1 = self.random_label1.pack_info()
self.label_info2 = self.random_label2.pack_info()
self.label_info3 = self.random_label3.pack_info()
self.switch()
def switch(self, *args):
var = str(self.choice_var.get())
if var == "Einführung":
self.random_label1.pack(self.label_info1)
self.random_label2.pack_forget()
self.random_label3.pack_forget()
if var == "Verschlüsseln":
self.random_label2.pack(self.label_info2)
self.random_label1.pack_forget()
self.random_label3.pack_forget()
if var == "Entschlüsseln":
self.random_label3.pack(self.label_info3)
self.random_label2.pack_forget()
self.random_label1.pack_forget()
myApp = App(window)
window.mainloop()
Related
import tkinter as tk
def quit():
global root
root.quit()
def prnt():
global usrinpt
lbl = tk.Label(text = usrinpt )
lbl.pack()
root = tk.Tk()
usrentr = tk.Entry()
usrinpt = str(usrentr.get())
usrentr.pack()
extbt = tk.Button(command=quit,text = 'Exit')
extbt.pack()
lblbt = tk.Button(command = prnt, text = 'Label')
lblbt.pack()
root.mainloop()
When I hit the Label button it just extends the window and doesn't print anything.
Thanks for the help!
You're adding the entry box then instantly trying to get the contents in the subsequent line. You should instead add a "submit" button that has the command set to star(usrentr.get())
I am creating a GUI, where I have placed three buttons for selecting a file. When I click the button it browse for a file and display the selected file path and I am trying to do it with a single browse function since the operation is same. I am bit confused to how I should proceed . Can anyone please help me out.
Thanks in advance.
Here is my code:
Browse_Files.py
from tkinter import filedialog
def Browse_File():
global Bfilepath
Bfilepath = filedialog.askopenfilename(filetypes = (("Please select the required file", "*"), ("All files", "*")))
return Bfilepath
Main.py
from tkinter import *
import sys
import fileinput
import Browse_Files
root = Tk()
root.geometry('1400x800')
root.title('Dr Configuration')
Heading = Label(root, font=('Times New Roman',50,'bold'),text = "Arxml
Configuration Tool").place(x=300,y=25)
BasepathLabel = Label(root,font=('Times New Roman',20,'bold'),text = " Base
arxml").place(x=200,y=150)
NewpathLabel= Label(root,font=('Times New Roman',20,'bold'),text = "
New/Unedited arxml").place(x=200,y=250)
InterfaceLabel = Label(root,font=('Times New Roman',20,'bold'),text = "
Interface_File").place(x=200,y=350)
BpathtoDisp = StringVar(None)
BpathEntry = Entry(root,font=('Times New Roman',18),textvariable=
BpathtoDisp,justify='left',width=48).place(x=500,y=150)
NpathtoDisp = StringVar(None)
NpathEntry = Entry(root,font=('Times New Roman',18),textvariable=
NpathtoDisp,justify='left',width=48).place(x=500,y=250)
InterPathtoDisp = StringVar(None)
InterPathEntry = Entry(root,font=('Times New Roman',18),textvariable=
NpathtoDisp,justify='left',width=48).place(x=500,y=350)
button1 = Button(root,text="...",height=1,width=3,command=lambda:Browse_Files.Browse_File()).place(x=1100,y=150)
button2 = Button(root,text="...",height=1,width=3,command=lambda:Browse_Files.Browse_File()).place(x=1100,y=250)
button3 = Button(root,text="...",height=1,width=3,command=lambda:Browse_Files.Browse_File()).place(x=1100,y=350)
root.mainloop()
You could create a class that contains the functionality to have a button, open a file dialog, store it and make it available to other parts of the program.
I have a similar widget that I use in many different programs
from tkinter import *
from tkinter import filedialog
class FileSelect(Frame):
def __init__(self,master,label="",**kw):
Frame.__init__(self,master)
self.configure(**kw)
self.file = StringVar()
self.Label = Label(self, text=label)
self.Label.config(width=10,anchor=E)
self.filenamebox = Entry(self,text=self.file)
self.filenamebox.config(width=50)
self.btnBrowse = Button(self,text='Browse',command=self.browse_file)
self.btnBrowse.config(width=10)
self.Label.grid(row=0,column=0,pady=5,sticky=E)
self.filenamebox.grid(row=0,column=1,pady=5)
self.btnBrowse.grid(row=0,column=2,pady=5,padx=5)
def browse_file(self):
filename = filedialog.askopenfilename(filetypes=[('All File','*.*')])
self.file.set(filename)
def get_filename(self):
return self.file.get()
def main():
root = Tk()
root.title("Example Widget")
fileSelect1 = FileSelect(root,label="My File 1")
fileSelect1.grid()
fileSelect2 = FileSelect(root,label="My File 2")
fileSelect2.grid()
root.mainloop()
if __name__ == '__main__':
main()
In your code if you want the value of the file selected use
fileSelect1.get_filename()
EDIT: I've created a new version that is only a Button 'with memory' to remember which item was selected by the file dialog. This will allow you to place using the place geometry manager (which I don't recommend). Its not complete but you should get the idea.
from tkinter import *
from tkinter import filedialog
class FileSelectButton(Button):
def __init__(self,master,**kw):
Button.__init__(self,master,text='Browse',command=self.browse_file,width=10,**kw)
self.file = StringVar()
def browse_file(self):
filename = filedialog.askopenfilename(filetypes=[('All File','*.*')])
self.file.set(filename)
def get_filename(self):
return self.file.get()
def main():
root = Tk()
root.geometry('1400x800')
root.title("Example Widget")
Label(root, font=('Times New Roman',50,'bold'),text = "Label1").place(x=200,y=150)
fileSelect1 = FileSelectButton(root)
fileSelect1.place(x=500,y=150)
Label(root, font=('Times New Roman',50,'bold'),text = "Label2").place(x=200,y=250)
fileSelect2 = FileSelectButton(root)
fileSelect2.place(x=500,y=250)
root.mainloop()
if __name__ == '__main__':
main()
I have a code where I have a drop down menu and what I need to do is that when I select an entry from the drop down list (ex: Send an email) and press on go, I need this to populate another tk window (child window).
I know I am doing something wrong but can not comprehend how to overcome this, I have been searching for a while but I am unable to find a solution or guidance on how to complete this.
Thanks in advance for your help with this!
from tkinter import *
root = Tk()
root.geometry("400x100")
#========================================
#Entry area to enter the number
labelmain = Label(root,text="Please enter number:")
labelmain.pack()
entryvar = StringVar(root)
entrymain = Entry(root, textvariable=entryvar,width=30)
entrymain.pack()
#========================================
#Create option drop down list:
lst = ["Save details to DB", "Send an email", "Copy format", "email", "View report"]
ddl = StringVar(root)
ddl.set(lst[0])
option = OptionMenu(root, ddl, *lst)
option.pack()
#========================================
#Function to get the values from drop down list
def ok():
print("value is: " + ddl.get())
#root.quit()
#=========================================
#Button to process the selection:
btnmain = Button(root,text="Go", command=ok)
btnmain.pack()
#=========================================
if ddl.get() == "Send an email":
samepmrdb = Tk()
samepmrdb.mainloop()
root.mainloop()
You are checking the value of ddl right after you open up your window. As you said in your question, you want some stuff happen after pressing the button so you need to put those codes under the command of said button.
Also, a tkinter app should only have one Tk() instance and one mainloop. When you want to open another window, you should use Toplevel().
def ok():
print("value is: " + ddl.get())
if ddl.get() == "Send an email":
samepmrdb = Toplevel()
#now you can populate samepmrdb as you like
If all you're looking to do is find a way to update a second tkinter window with the selection from an OptionMenu on the first tkinter window this can be achieved easily using the below code:
from tkinter import *
class App:
def __init__(self, master):
self.master = master
self.top = Toplevel(master)
self.master.withdraw()
self.var = StringVar()
self.var.set("Example1")
self.option = OptionMenu(self.top, self.var, "Example1", "Example2", "Example3", "Example4")
self.button = Button(self.top, text="Ok", command=lambda:self.command(self.var))
self.label = Label(self.master)
self.option.pack()
self.button.pack()
self.label.pack()
def command(self, var):
self.master.deiconify()
self.label.configure(text=var.get())
self.label.pack()
root = Tk()
app = App(root)
root.mainloop()
This creates a Toplevel widget which contains an OptionMenu and Button widget. The Button widget will then output the selection from the OptionMenu widget when pressed.
This kind of logic can be used for all sorts of things and it's relatively simple to pass information from one window to another, provided this is what your question is asking.
I am having trouble with using a key binding to change the value of a label or any parameter.
This is my code:
from tkinter import*
class MyGUI:
def __init__(self):
self.__mainWindow = Tk()
#self.fram1 = Frame(self.__mainWindow)
self.labelText = 'Enter amount to deposit'
self.depositLabel = Label(self.__mainWindow, text = self.labelText)
self.depositEntry = Entry(self.__mainWindow, width = 10)
self.depositEntry.bind('<Return>', self.depositCallBack)
self.depositLabel.pack()
self.depositEntry.pack()
mainloop()
def depositCallBack(self,event):
self.labelText = 'change the value'
print(self.labelText)
myGUI = MyGUI()
When I run this, I click the entrybox and hit enter, hoping that the label will change value to 'change the value'. However, while it does print that text, the label remains unchanged.
From looking at other questions on similar problems and issues, I have figured how to work with some of this outside a class, but I'm having some difficulties with doing it inside a class.
self.labelText = 'change the value'
The above sentence makes labelText change the value, but not change depositLabel's text.
To change depositLabel's text, use one of following setences:
self.depositLabel['text'] = 'change the value'
OR
self.depositLabel.config(text='change the value')
You can also define a textvariable when creating the Label, and change the textvariable to update the text in the label.
Here's an example:
labelText = StringVar()
depositLabel = Label(self, textvariable=labelText)
depositLabel.grid()
def updateDepositLabel(txt) # you may have to use *args in some cases
labelText.set(txt)
There's no need to update the text in depositLabel manually. Tk does that for you.
Use the config method to change the value of the label:
top = Tk()
l = Label(top)
l.pack()
l.config(text = "Hello World", width = "50")
Here is another one, I think. Just for reference.
Let's set a variable to be an instantance of class StringVar
If you program Tk using the Tcl language, you can ask the system to let you know when a variable is changed. The Tk toolkit can use this feature, called tracing, to update certain widgets when an associated variable is modified.
There’s no way to track changes to Python variables, but Tkinter
allows you to create variable wrappers that can be used wherever Tk
can use a traced Tcl variable.
text = StringVar()
self.depositLabel = Label(self.__mainWindow, text = self.labelText, textvariable = text)
# ^^^^^^^^^^^^^^^^^^^
def depositCallBack(self,event):
text.set('change the value')
I made a small tkinter application which is sets the label after button clicked
#!/usr/bin/env python
from Tkinter import *
from tkFileDialog import askopenfilename
from tkFileDialog import askdirectory
class Application:
def __init__(self, master):
frame = Frame(master,width=200,height=200)
frame.pack()
self.log_file_btn = Button(frame, text="Select Log File", command=self.selectLogFile,width=25).grid(row=0)
self.image_folder_btn = Button(frame, text="Select Image Folder", command=self.selectImageFile,width=25).grid(row=1)
self.quite_button = Button(frame, text="QUIT", fg="red", command=frame.quit,width=25).grid(row=5)
self.logFilePath =StringVar()
self.imageFilePath = StringVar()
self.labelFolder = Label(frame,textvariable=self.logFilePath).grid(row=0,column=1)
self.labelImageFile = Label(frame,textvariable = self.imageFilePath).grid(row = 1,column=1)
def selectLogFile(self):
filename = askopenfilename()
self.logFilePath.set(filename)
def selectImageFile(self):
imageFolder = askdirectory()
self.imageFilePath.set(imageFolder)
root = Tk()
root.title("Geo Tagging")
root.geometry("600x100")
app = Application(root)
root.mainloop()
There are many ways to tackle a problem like this. There are many ways to do this. I'm going to give you the most simple solution to this question I know. When changing the text of a label or any kind of wiget really. I would do it like this.
Name_Of_Label["text"] = "Your New Text"
So when I apply this knowledge to your code. It would look something like this.
from tkinter import*
class MyGUI:
def __init__(self):
self.__mainWindow = Tk()
#self.fram1 = Frame(self.__mainWindow)
self.labelText = 'Enter amount to deposit'
self.depositLabel = Label(self.__mainWindow, text = self.labelText)
self.depositEntry = Entry(self.__mainWindow, width = 10)
self.depositEntry.bind('<Return>', self.depositCallBack)
self.depositLabel.pack()
self.depositEntry.pack()
mainloop()
def depositCallBack(self,event):
self.labelText["text"] = 'change the value'
print(self.labelText)
myGUI = MyGUI()
If this helps please let me know!
I've searched and found a few things on parent windows in python but that is not what I was looking for. I am trying make a simple program that opens a window and another window after that when the previous one is closed. I was also trying to implement some kind of loop or sleep time to destroy the window by default if the user does not. This is what I have (I'm new please don't laugh)
from tkinter import *
import time
root = Tk()
i = 0
if i < 1:
root.title("title")
logo = PhotoImage(file="burger.gif")
w1 = Label(root, image=logo).pack()
time.sleep(3)
root.destroy()
i = i + 1
if i == 1:
root.title("title")
photoTwo = PhotoImage(file="freedom.gif")
labelTwo = Label(root, image=photoTwo).pack()
time.sleep(3)
root.destroy()
i = i + 1
mainloop.()
Perhaps you're looking for something like this:
from tkinter import *
import time
def openNewWindow():
firstWindow.destroy()
secondWindow = Tk()
secondWindow.title("Second Window")
photoTwo = PhotoImage(file="freedom.gif")
labelTwo = Label(secondWindow, image=photoTwo).pack()
secondWindow.mainloop()
firstWindow = Tk()
firstWindow.title("First Window")
logo = PhotoImage(file="burger.gif")
w1 = Label(firstWindow, image=logo).pack()
closeBttn = Button(firstWindow, text="Close!", command=openNewWindow)
closeBttn.pack()
firstWindow.mainloop()
This creates a button in the first window, which the user clicks. This then calls the openNewWindow function, which destroys that window, and opens the second window. I'm not sure there's a way to do this using the window exit button.
To get create a more sustainable window creation, use this:
from tkinter import *
import time
def openThirdWindow(previouswindow):
previouswindow.destroy()
thirdWindow = Tk()
thirdWindow.title("Third Window")
photoTwo = PhotoImage(file="freedom.gif")
labelTwo = Label(thirdWindow, image=photoTwo).pack()
thirdWindow.mainloop()
def openSecondWindow(previouswindow):
previouswindow.destroy()
secondWindow = Tk()
secondWindow.title("Second Window")
photoTwo = PhotoImage(file="freedom.gif")
labelTwo = Label(secondWindow, image=photoTwo).pack()
closeBttn = Button(secondWindow, text="Close!", command= lambda: openThirdWindow(secondWindow))
closeBttn.pack()
secondWindow.mainloop()
def openFirstWindow():
firstWindow = Tk()
firstWindow.title("First Window")
logo = PhotoImage(file="burger.gif")
w1 = Label(firstWindow, image=logo).pack()
closeBttn = Button(firstWindow, text="Close!", command= lambda: openSecondWindow(firstWindow))
closeBttn.pack()
firstWindow.mainloop()
openFirstWindow()
This places the opening of each window in a seperate function, and passes the name of the window through the button presses into the next function. Another method would be setting the window names as global, but this is messy.
The function "lambda:" calls the function, in tkinter you must type this if you want to pass something through a command.
We initiate the whole process first first called "openFirstWindow()"