I have a custom Entry "self.name_e" on the second window "Demo 2" but anytime I run the code the custom entry only shows up on the first window "Demo 1"...
self.name_e is used to receive the entry on Window 2 "Demo 2"
The AutocompleteEntry is the custom Entry class that is used by windows two
How do I fix this?
import tkinter as tk
#To shorten the code for perfect readability I chose to remove the content of the AutocompleteEntry class
class AutocompleteEntry(Entry):...
class Demo1:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
self.master.geometry("1366x768+0+0")
self.button1.pack()
self.frame.pack()
def new_window(self):
self.newWindow = tk.Toplevel(self.master)
self.app = Demo2(self.newWindow)
class Demo2:
def __init__(self, master):
self.master = master
autocompleteList = [ 'Milo tin', 'Shito small' ]
def matches(fieldValue, acListEntry):
pattern = re.compile(re.escape(fieldValue) + '.*', re.IGNORECASE)
return re.match(pattern, acListEntry)
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.master.geometry("1366x768+0+0")
self.quitButton.pack()
self.frame.pack()
#AutocompleteEntry is a custom Entry which is also a class on it own
self.name_e = AutocompleteEntry(autocompleteList, listboxLength=10, width=20, font=('arial 18 bold'), matchesFunction=matches)
self.name_e.place(x=350, y=150)
def close_windows(self):
self.master.destroy()
def main():
root = tk.Tk()
app = Demo1(root)
root.mainloop()
if __name__ == '__main__':
main()
Related
Am new to this so apologies for the basic question
I am trying to set an input box to take letters and numbers
Unfortunately I can only set this field to numbers by using str()
I have tried messing with the code but it will not allow me to use letters
What should I be using instead of str()?
As you can see in my code example, I can only set the username and password to a numerical value rather than alpha numeric values
I believe that I have imported all the correct modules from tk
Have I set the below definitions incorrectly?
- self.Username = StringVar()
- self.Password = StringVar()
Thanks
from tkinter import*
import tkinter.messagebox
from tkinter import ttk
import random
import time
import datetime
def main():
root = Tk()
app = Window1(root)
class Window1:
def __init__(self, master):
self.master =master
self.master.title("Notification Monitoring System")
self.master.geometry('1350x750+0+0')
self.master.config(bg ='white')
self.frame = Frame(self.master, bg ='white')
self.frame.pack()
self.Username = StringVar()
self.Password = StringVar()
self.lblTitle = Label(self.frame, text = 'Welcome to Notification Monitoring', font=('arial',50,'bold'), bg='white',
fg='black')
self.lblTitle.grid(row=0, column=0, columnspan=2, pady=40)
#==============================Frames================================================================
self.LoginFrame1 = LabelFrame(self.frame, width=1350, height=600
,font=('arial',20,'bold'),relief='ridge',bg='pale green', bd=20)
self.LoginFrame1.grid(row=1, column=0)
self.LoginFrame2 = LabelFrame(self.frame, width=1000, height=600
,font=('arial',20,'bold'),relief='ridge',bg='pale green', bd=20)
self.LoginFrame2.grid(row=2, column=0)
#==============================Label And Entry=======================================================
self.lblUsername=Label(self.LoginFrame1, text = 'Username',font=('arial',20,'bold'),bd=22,
bg='pale green', fg='black')
self.lblUsername.grid(row=0,column=0)
self.txtUsername=Entry(self.LoginFrame1,font=('arial',20,'bold'),textvariable= self.Username)
self.txtUsername.grid(row=0,column=1, padx=119)
self.lblPassword=Label(self.LoginFrame1, text = 'Password',font=('arial',20,'bold'),bd=22,
bg='pale green', fg='black')
self.lblPassword.grid(row=1,column=0)
self.txtPassword=Entry(self.LoginFrame1,font=('arial',20,'bold'),show='*', textvariable= self.Password)
self.txtPassword.grid(row=1,column=1, columnspan=2, pady=30)
#==============================Buttons===============================================================
self.btnLogin = Button(self.LoginFrame2, text = 'Login', width = 17,font=('arial',20,'bold'),
command =self.Login_System)
self.btnLogin.grid(row=3,column=0, pady=20, padx=8)
self.btnReset = Button(self.LoginFrame2, text = 'Clear', width = 17,font=('arial',20,'bold'),
command =self.Reset)
self.btnReset.grid(row=3,column=1, pady=20, padx=8)
self.btnExit = Button(self.LoginFrame2, text = 'Exit', width = 17,font=('arial',20,'bold'),
command =self.iExit)
self.btnExit.grid(row=3,column=2, pady=20, padx=8)
#==============================Buttons===========================================================
def Login_System(self):
u =(self.Username.get())
p =(self.Password.get())
if (u ==str(123456789) and p ==str(987654321)):
self.newWindow = Toplevel(self.master)
self.app = Window2(self.newWindow)
else:
tkinter.messagebox.askyesno("Notification Monitoring System", "Invalid login details")
self.Username.set("")
self.Password.set("")
self.txtUsername.focus()
def Reset(self):
self.Username.set("")
self.Password.set("")
self.txtUsername.focus()
def iExit(self):
self.iExit = tkinter.messagebox.askyesno("Notification Monitoring System", "Confirm you want to exit")
if self.iExit > 0:
self.master.destroy()
else:
command = self.new_window
return
def new_window(self):
self.newWindow = Toplevel(self.master)
self.app = Window2(self.newWindow)
class Window2:
def __init__(self, master):
self.master =master
self.master.title("Notification Monitoring System")
self.master.geometry('1350x750+0+0')
self.master.config(bg ='cadet blue')
self.frame = Frame(self.master, bg ='powder blue')
self.frame.pack()
#====================================================================================================
#==============================New window code here==================================================
#===================================================================================================
if __name__== '__main__':
root = Tk()
application = Window1(root)
root.mainloop()
Your question is unclear but I'll try and answer it.
To take input as a number, use:
>>>a = int(input("Enter :"))
Enter :5
>>>print(a*5)
25
I am trying to make a GUI for my program but I have changed my code a lot and I saw that GUI misses one frame but it was fine before.
Could anyone help me and tell why a frame with a button does not appear on the bottom?
Whole "button_part" object does not appear.
from tkinter import *
import tkinter as tk
import os
import glob
BOUNDS = ["Last week", "Last 2 weeks", "Last 3 weeks"]
class settings_part:
path_to_copy = 0
def __init__(self, master, update_func):
path_to_copy = StringVar()
settings_frame = Frame(master, background="")
settings_frame.pack(side=TOP, fill=X)
date_bound = StringVar()
date_bound.set(BOUNDS[1])
date_option = OptionMenu(settings_frame, date_bound, *BOUNDS, command=update_func)
date_option.config(background="#732c30")
date_option.config(foreground="white")
date_option.config(bd=0)
date_option.pack(side=LEFT, padx=5, pady=5)
path_to_copy.set("~/Python/usun")
box_with_path = Entry(settings_frame, textvariable=path_to_copy)
box_with_path.pack(side=RIGHT, padx=5, pady=5)
# s = path_to_copy.get()
class songs_part:
def __init__(self, master, root):
self.songs_frame = Frame(master)
self.update_songs(root.list_of_songs)
self.songs_frame.pack()
def update_songs(self, l):
for song in l:
c = Checkbutton(self.songs_frame, text=song[0], variable=song[1])
c.pack()
class button_part:
def __init__(self, master, copyFunc):
self.button_frame = Frame(master)
btn_image = PhotoImage(file="copybtn.png")
self.copy_button = Button(self.button_frame, command=copyFunc, text="Copy",
image=btn_image, highlightthickness=0, bd=0, activebackground="#732c30")
self.copy_button.pack()
class App:
def __init__(self):
root = Tk()
root.title("Copying songs")
root.geometry("500x500")
root.option_add("*Font", "Calibra")
back_image = PhotoImage(file="back.png")
self.window = Label(root, image=back_image)
self.window.pack(fill="both", expand="yes")
self.list_of_songs = list()
self.make_list_of_songs()
self.set_part = settings_part(self.window, self.update_list)
self.son_part = songs_part(self.window, self)
self.but_part = button_part(self.window, self.copy_songs)
root.mainloop()
def make_list_of_songs(self):
owd = os.getcwd()
os.chdir("/home/stanek/Music/usun")
for file in glob.glob("*.mp3"):
self.list_of_songs.append([file, tk.IntVar()])
os.chdir(owd)
def copy_songs(self):
for s in self.list_of_songs:
print(s)
def update_list(self, arg):
print("updating list with songs from " + arg)
self.son_part = songs_part(self.window, self)
if __name__ == '__main__':
App()
You never pack the button frame.
My problem is that I want my code to take an entry from the user,
then the value that the user entered will be displayed on the toplevel page pf the previous class.
I have searched quite a bit but none of the solution worked for me.
So could any one of you generously tell me how I can change my code so that I can actually display the value entered by the user in the toplevel page?
Many thanks<3
import Tkinter as tk
class Demo2:
def __init__(self, master):
self.master = master
self.quitButton = tk.Button(self.master, text = 'Quit', width = 25, command = self.close_windows)
self.goButton = tk.Button(self.master, text = "Go", command = self.window_one)
global EnteredNumber
self.EnteredNumber = tk.IntVar()
self.entry = tk.Entry(self.master,textvariable=self.EnteredNumber)
VertexNumber = self.EnteredNumber.get()
self.goButton.pack()
self.entry.pack()
self.quitButton.pack()
def close_windows(self):
self.master.destroy()
def window_one(self):
self.window_one = tk.Toplevel(self.master)
self.app = Demo3(self.window_one)
class Demo3():
def __init__(self, master):
self.master = master
self.label1 = tk.Label(self.master, text=EnteredNumber)
self.label = tk.Label(self.master, text="Hi")
self.label.pack()
self.label1.pack()
def main():
root = tk.Tk()
app = Demo2(root)
root.overrideredirect(True)
root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))
root.mainloop()
if __name__ == '__main__':
main()
Send the value of the Entry through to the __init__ of Demo3()
First the changes to window_one():
def window_one(self):
enterednumber = self.entry.get() # Grab the value in the Entry
self.window_one = tk.Toplevel(self.master)
self.app = Demo3(self.window_one, enterednumber) # Send it to Demo3 as an argument
And then Demo3()
class Demo3():
def __init__(self, master, enterednumber): # Reconfigure __init__ to accept the new arg
self.master = master
self.label1 = tk.Label(self.master, text=enterednumber)
self.label = tk.Label(self.master, text="Hi")
self.label.pack()
self.label1.pack()
Below is my code, it runs but I'm not sure how to get the "Run text" button to prompt me to open text file in new window, currently a new window appears with a "Quit" button, nothing else.
import tkFileDialog
import Tkinter as tk
from Tkinter import *
import logging
logging.basicConfig(filename= "log_file.txt", filemode = "w", level=logging.DEBUG, format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')
class HomeScreen:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.button1 = tk.Button(self.frame, text = 'Run Text', width = 25, command = self.new_window)
self.button1.pack()
self.frame.pack()
def openFile(self):
openfile = tkFileDialog.askopenfile().read()
text= open(openfile, 'r').read()
T.insert(1.0, openfile)
T = Text(height=10, width=100)
T.pack()
T.insert(END, "Select file to input")
B = Button(root, text="Open", command=openFile)
B.pack()
mainloop()
return
def new_window(self):
self.newWindow = tk.Toplevel(self.master)
self.app = Quit(self.newWindow)
class Quit:
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
self.quitButton.pack()
self.frame.pack()
def close_windows(self):
self.master.destroy()
def main():
root = tk.Tk()
app = HomeScreen(root)
app = Quit(root)
root.mainloop()
if __name__ == '__main__':
main()
I'm sure my code is very messy as I'm just a beginner, some parts may not be needed, any advice would be greatly appreciated.
I've simplified your code a bit, but I've also enhanced it a little. I use askopenfilename rather than askopenfile, so we can get the file name and display it in the titlebar of each Toplevel window containing a Text widget.
import tkFileDialog
import Tkinter as tk
class HomeScreen:
def __init__(self, master):
self.master = master
frame = tk.Frame(master)
frame.pack()
button = tk.Button(frame, text='Show Text', width=25, command=self.open_file)
button.pack()
button = tk.Button(frame, text='Quit', width=25, command=master.destroy)
button.pack()
master.mainloop()
def open_file(self):
filename = tkFileDialog.askopenfilename()
if not filename:
#User cancelled
return
with open(filename) as f:
filedata = f.read()
window = tk.Toplevel(self.master)
window.title(filename)
text = tk.Text(window, height=10, width=100)
text.pack()
text.insert(1.0, filedata)
def main():
root = tk.Tk()
HomeScreen(root)
if __name__ == '__main__':
main()
To display the text file one word at a time you can replace the open_file method with the version below. You'll also need to add the show_word method. I'm not claiming that this is the best way to achieve this effect, but at least it works. :)
def show_word(self, word):
self.text.delete(1.0, tk.END)
self.text.insert(tk.END, word)
def open_file(self):
filename = tkFileDialog.askopenfilename()
if not filename:
#User cancelled
return
with open(filename) as f:
filedata = f.read()
words = filedata.split()
window = tk.Toplevel(self.master)
window.title(filename)
self.text = text = tk.Text(window, height=10, width=100)
text.pack()
delta = 1000 #in millseconds
delay = 0
for word in words:
window.after(delay, lambda word=word: self.show_word(word))
#print word
delay += delta
If you want that "Run text" open's a file dialog change called method:
self.button1 = tk.Button(self.frame, text = 'Run Text', width = 25, command = self.openFile)
I'm making a quiz app with tkinter and i want each question in a new window, but after I create a new window i can't figure out how to destroy the previous window. Here is a rough simplified excerpt of my code:
from tkinter import *
class q1:
def __init__(self, master):
self.master = master
Label(self.master, text='What is 3 + 3?').grid()
self.option_1 = Button(self.master, text='5', command = self.incorrect)
self.option_1.grid()
self.option_2 = Button(self.master, text='6', command = self.correct)
self.option_2.grid()
def correct(self):
self.option_1.config(state=DISABLED)
self.option_2.config(state=DISABLED)
Label(self.master, text='Correct').grid()
Button(self.master, text='Next Question', command = self.nextq).grid()
def incorrect(self):
self.option_1.config(state=DISABLED)
self.option_2.config(state=DISABLED)
Label(self.master, text='Incorrect').grid()
Button(self.master, text='Next Question', command = self.nextq).grid()
def nextq(self):
q2(Toplevel(self.master))
class q2:
def __init__(self, master):
self.master = master
Label(self.master, text='Question 2').grid()
def window():
root = Tk()
q1(root)
root.mainloop()
if __name__ == '__main__':
window()
UPDATED VERSION
from Tkinter import *
import random
class Ask:
def __init__(self, parent,question,right,wrong):
self.answer=right
self.top=top=Toplevel(parent)
Label(self.top, text=question,width=25).grid()
a1=random.choice([right,wrong])
self.option_1 = Button(self.top, text=a1, width=25,command = lambda: self.check(1))
self.option_1.grid()
a2=right
if a1==right:
a2=wrong
self.option_2 = Button(self.top, text=a2, width=25, command = lambda: self.check(2))
self.option_2.grid()
def check(self,pressed):
if pressed==1:
ans=self.option_1['text']
else:
ans=self.option_2['text']
if ans==self.answer:
self.correct()
else:
self.incorrect()
def correct(self):
self.option_1.config(state=DISABLED)
self.option_2.config(state=DISABLED)
Label(self.top, text='Correct').grid()
Button(self.top, text='Next Question', command = self.top.destroy).grid()
def incorrect(self):
self.option_1.config(state=DISABLED)
self.option_2.config(state=DISABLED)
Label(self.top, text='Incorrect').grid()
Button(self.top, text='Next Question', command = self.top.destroy).grid()
class QUIZ:
def __init__(self, questionsdict):
self.root=Tk()
self.root.withdraw()
self.questions(questionsdict)
self.root.deiconify()
c=Button(self.root, text='Click me to exit', command=self.root.destroy, width=30).grid(row=2, sticky='ew')
Label(self.root, text='Quiz is Complete', width=30, background='red').grid(row=0, sticky='ew')
mainloop()
def questions(self,questionsdict):
for k in questionsdict.keys():
right=questionsdict[k][0]
wrong=questionsdict[k][1]
b=Ask(self.root, k, right,wrong )
self.root.wait_window(b.top)
put quiz questions in a dictionary in the format: {question:[correctchoice,incorrectchoice]} and use that as the parameter when calling the Question Class
questions={'What is 3+3':['6','8'], 'What is the capital of Alaska': ['Juno','Anchorage']}
QUIZ(questions)