I'm trying to open a second window (defined by the function 'learn') from the main program - the window opens with no problem but the buttons/images don't show up. Does anyone know what I'm doing wrong? All the images are .gif files and sit in the same folder as the program.
I wrote the code under 'learn' in a separate python file. Initially I had tried to open that file as a separate program but it didn't work.
from tkinter import *
import linecache
import os
root = Tk()
root.geometry('1200x800') #Dimensions of the window
root.title("stud(y)ious") #title of the window
container1 = Frame(root)
container1.pack(side = TOP, anchor = W)
container2= Frame(root) #Bottom container
container2.pack(side = BOTTOM,pady = 50) #space between the bottom of the timetable and the two buttons; initially this was cropping the timetable too much so this value was DECREASED in order to shorten the amount of padding that exists around the two buttons at the bottom
#All the images used on the home page; keeping them all in one place so they can be eaisly replaced by anotehr programmer if need be
imgNote = PhotoImage(file='img_note.gif') #'N O T E'
imgHeader = PhotoImage(file='img_title.gif') #'stud(y)ious' 'T I M E T A B L E'
imgTimetable = PhotoImage(file='btn_timetable.gif') #replacable timetable image
imgCreateBtn = PhotoImage(file='btn_create.gif') #'create'
imgLearnBtn = PhotoImage(file='btn_learn.gif') #'learn'
toolbar = Canvas()
Header = Label(toolbar, image = imgHeader).pack() #creation of header, space for imgHeader; above and seperated from main buttons
toolbar.pack()
def destroy(): #closing the window
root.destroy()
def create(): #The window that appears when the 'create' button is clicked
toplevel = Toplevel()
labelCreateHeader = Label(toplevel, image=imgNote) #header graphic
labelCreateHeader.pack()
labelCreateText = Label(toplevel, text=txtCreate) #text (from variable noted below)
labelCreateText.pack()
def learn(): #The window that appears when the 'learn' button is clicked
window1 = Tk()
window1.geometry('1200x800')
window1.title("stud(y)ious: Learn") #title of the window, colon to show connection to studyious_main.py
#Opens the questions file (in read mode) and makes a list of them, one per line
with open('studyious_questions.txt', 'r+') as questionfile:
questions = questionfile.readlines()
#Takes off the '\n' from the end of each line so they are neatly presented and easy to read
questions = [i.strip('\n') for i in questions]
#reading answers; holds a string only - default value ""; type checking
ans1 = StringVar()
ans2 = StringVar()
ans3 = StringVar()
ans4 = StringVar()
ans5 = StringVar()
answers = []
for i in range(1,9):
answers.append(linecache.getline('studyious_answers.txt', i))
answers = [i.strip('\n') for i in answers]
def destroy2():
window1.destroy() #closes window, function attached to '⬅' button
def answering(answer, index): #The window that appears when the 'create' button is clicked
toplevel = Toplevel()
labelCorrectHeader = Label(toplevel, text=txtInfoCorrect, image=imgCorrect) #header graphic
labelCorrect = Label(toplevel, text=txtInfoCorrect) #text (from variable noted below)
labelIncorrectHeader = Label(toplevel, text=txtInfoIncorrect, image=imgIncorrect)
labelIncorrect = Label(toplevel, text=txtInfoIncorrect)
if answer == answers[index]: #selection structure to decide whether the 'correct' (if) or 'incorrect' (else) window pops up
labelCorrectHeader.pack()
labelCorrect.pack()
else:
labelIncorrectHeader.pack()
labelIncorrect.pack()
#The following two text variable were written using triple quotations so the program would register line breaks effectively
txtInfoCorrect = """
Keep up the good work!
Remember, for every 10 questions, take a lil' break <3
"""
txtInfoIncorrect = """
Better luck next time!
Keep going, you can do it!
"""
container01 = Frame(window1)
container01.pack(anchor = W)
ButtonQuit = Button(container01, command=destroy2) #FIXME should open the other python file, containing the homepage
ButtonQuit["text"] = "⬅"
ButtonQuit.pack(side = LEFT, padx = 10, pady = 8)
#Directory of images used in this program
imgCorrect = PhotoImage(file='img_correct.gif')
imgIncorrect = PhotoImage(file='img_incorrect.gif')
imgAnswer = PhotoImage(file='btn_answer.gif')
imgHeaderb = PhotoImage(file='img_header.gif')
toolbar1 = Canvas()
Header1 = Label(toolbar1, image = imgHeaderb).pack() #Placing the header image (img_header) at the top of the page
toolbar1.pack()
#THE QUESTIONS
question1 = Label(window1, text=questions[0]).pack(pady = 10) #states the question according to it's number in the list (e.g this one is 0 because it is the first item in the studyious_questions.txt file
#pady refers to the space between each of teh questions (so things dont look too cluttered and unprofessional)
entry1= Entry(window1, textvariable = ans1) #User can cnter answer to to entry box
entry1.pack()
ButtonAnswer1 = Button(image = imgAnswer,command=lambda:answering(ans1.get(), 0)).pack() #answer button, when clicked entered answer will be checked against teh answer recorded in studyious_answers.txt to see if it is correct
#For example, for the example above, the answer entered by the user is checked against the first answer in the list of answers (index of 0) to see if it correct; promopting a response from the variable 'answering' (which will either produce the 'correct' or 'incorrect dialogue window)
question2 = Label(window1, text=questions[1]).pack(pady = 10)
entry2= Entry(window1, textvariable = ans2)
entry2.pack()
ButtonAnswer2 = Button(image = imgAnswer,command=lambda:answering(ans2.get(), 1)).pack()
question3 = Label(window1, text=questions[2]).pack(pady = 10)
entry3= Entry(window1, textvariable = ans3)
entry3.pack()
ButtonAnswer3 = Button(image = imgAnswer,command=lambda:answering(ans3.get(), 2)).pack()
question4 = Label(window1, text=questions[3]).pack(pady = 10)
entry4= Entry(window1, textvariable = ans4)
entry4.pack()
ButtonAnswer4 = Button(image = imgAnswer,command=lambda:answering(ans4.get(), 3)).pack()
question5 = Label(window1, text=questions[4]).pack(pady = 10)
entry5= Entry(window1, textvariable = ans5)
entry5.pack()
ButtonAnswer5 = Button(image = imgAnswer,command=lambda:answering(ans5.get(), 4)).pack()
window1.mainloop()
txtInfo = """
text
"""
txtCreate = """
text
"""
def timetable():
toplevel = Toplevel() #Ensure window pops up above the main window as a pop up window
labelTimetableHeader = Label(toplevel, image=imgNote) #header graphic to match aesthetic of the rest of the program
labelTimetableHeader.pack()
labelTimetableText = Label(toplevel, text=txtInfo) #The main body of text (as seen above in txtInfo)
labelTimetableText.pack()
btnQuit = Button(container1,command=destroy) #Quit button, closes window
btnQuit["text"] = "Quit"
btnQuit.pack(side = LEFT, padx = 10, pady = 8) #the difference between the top and left padding is that there is automatically two points of padding from the top of the window
TimetableButton = Button(image = imgTimetable,command=timetable).pack() #a replacable image that allows users to enter place their own timetable on the home page
#Initially the button sat squished in the corner whih made the finishing of the home page look very rough, cluttered and unprofessional
#Button 1; opens a small window giving the user details of how to enter the questions and answers they wish to test themselves on
btnCreate = Button(container2, image = imgCreateBtn,command=create).pack(side = LEFT, padx =100) #padding around teh sides seperates the two buttons - 'create' and 'learn'
#Button 2; redirect to the quiz program, opening another window with the quiz program
btnLearn = Button(container2, image = imgLearnBtn,command=learn).pack(side = BOTTOM, padx = 100)
root.mainloop()
You forgot to put window1 as the master of any of your buttons like this one:
ButtonAnswer1 = Button(image = imgAnswer,command=lambda:answering(ans1.get(), 0)).pack()
add window1 to all your ButtonAnswer1-5:
ButtonAnswer1 = Button(window1, image = imgAnswer,command=lambda:answering(ans1.get(), 0)).pack()
Related
im relatively new to coding and am trying to display an image on tkinter, i have it set so when you press on a button on the first screen it will open to another screen - i have got this working fine my issue is that when the new window is opened the image that should be on the second screen goes onto the first screen, and i cannot work out how to fix it. I dont get any errors it just puts the image in the middle of the first screen, I hope this makes sense. Thanks
The code is below: (for the second screen that should be displaying the image but isnt)
from tkinter import *
window2 = Tk()
window2.geometry("1920x1200")
Namearea = Label(window2, text = "Please Name the Prebuild: ")
Namearea.pack()
e = Entry(window2, width=50, borderwidth=3, bg="Light Grey", fg="black")
e.pack()
e.insert(0, "Remove this text and Enter the name of your prebuild: ")
# this is the part for the image
img3 = PhotoImage(file=r"C:\Tkinter\ComputerImage.png ")
picture1 = Label(image=img3)
picture1.pack()
SaveAndContinue = Button(window2, text = "Save and Return to Main Menu", padx = 75, pady = 20, bg = "Light Grey")
SaveAndContinue.pack()
LinkTitle = Label(window2, text = "Here are some links to purchase the parts from:")
Link1 = Label(window2, text = "Scorptec: www.scorptec.com.au/")
Link2 = Label(window2, text = "Centre-Com: www.centrecom.com.au/")
LinkTitle.pack()
Link1.pack()
Link2.pack()
Since you used multiple instances of Tk() (one for first window, one for second window), you need to specify the parent for picture1 and img3:
img3 = PhotoImage(master=window2, file=r"C:\Tkinter\ComputerImage.png")
picture1 = Label(window2, image=img3)
picture1.pack()
However, you should avoid using multiple instances of Tk(). Better change second instance of Tk() to Toplevel().
Hey you forgot to mention the window name in picture1 = Label(image=img3)
here is the right one the mistake
# this is the part for the image
img3 = PhotoImage(file=r"C:\\Tkinter\\ComputerImage.png ")
picture1 = Label(window2,image=img3)
picture1.pack()
And the
error error _tkinter.TclError: image "pyimage4" doesn't exist -
You have to use Toplevel() in second window
window2=Toplevel ()
It works for me
I have looked at every posting I can find, but still can't seem to fix the issue. I have a tkinter app and am trying to add radiobuttons. No matter what I try, the buttons come up with both preselected. I'd like them to appear blank.
Please help me. am trying to figure Python out and have been able to handle the screen scraping, logging into a site that tries hard to lock out applications, but can't get this detail straight. Thee code is quite long, but i think i am including the relevant section. The problem area is the last section at the bottom.
Thanks in advance for any help provided.
Create the User Name/Password Heading Area
self.heading_prompt = tk.Label(self.label_entry_frame, text='LOG `enter code here`on\ `ASSSISTANT')
self.heading_prompt.config(fg='blue', font('times',heading_font, 'bold'))
self.heading_prompt.pack(side = 'left')
self.label_entry_frame.place(x = 112, y=100)
# User credentials - prompt
self.user_name_prompt = tk.Label(self.name_entry_frame, text='Select `enter code here`User: ')
self.user_name_prompt.config(fg='green', font=('times', ``regular_font, 'bold'))
self.user_name_prompt.pack(side = 'left')
# Create Course Name Listbox
self.user_name_selected = tk.Listbox(self.name_entry_frame,width =7, `enter code here`height = 2, highlightcolor="green",selectmode = 'single', `enter code here`exportselection = "False" )
self.user_name_selected.config(fg='green', font=enter code here`enter code here`('times',regular_font, 'bold'))
self.user_name_selected.insert(1, "Margy")
self.user_name_selected.insert(2, "Steve")
self.user_name_selected.pack(side = 'left')
self.name_entry_frame.place(x=10,y=130)
# Position Cursor into User Name Listbox
self.user_name_selected.focus_set()
# User credentials - buttons
self.user_no = 0
#self.user_no.set(value = 0)
user_rb_1 = tk.Radiobutton(self.name_entry_frame, text = "Margy", variable = self.user_no, value = 1)
user_rb_1.config(fg='green', font=('times',regular_font, 'bold'))
user_rb_1.pack(side = "left")
user_rb_2 = tk.Radiobutton(self.name_entry_frame, text = "Steve", variable = self.user_no, value = 1)
user_rb_2.config(fg='green', font=('times',regular_font, 'bold'))
user_rb_2.pack(side = "left")
self.name_entry_frame.place(x=30, y=160)
The Radiobutton's variable is supposed to be a tkinter variable:
import tkinter as tk
root = tk.Tk()
user_no = tk.IntVar()
user_rb_1 = tk.Radiobutton(root, text = "Margy", variable = user_no, value = 1)
user_rb_1.pack()
user_rb_2 = tk.Radiobutton(root, text = "Steve", variable = user_no, value = 2)
user_rb_2.pack()
root.mainloop()
You can then get the value selected (1 or 2) whenever you want with user_no.get(). As long as nothing's selected it will be 0.
First time coding in Python with tkinter; online searches and the manual have not worked (for me).
Below is an example of the issue:
(I would put an image, but I'm sub 10 reputation so I cannot).
I have a definition that loads the other parts of the system named Load_Main_Menu. You can access the food menu, drink menu, etc from here. For ease of use I have edited it so that you don't have to write out code to get it to work.
I have a definition that displays the main menu, buttons the user can use to get into other parts of the system. I've reduced the code I already have so you can copy and paste it and see what I mean:
import tkinter#Imports Tkinter. Used for the user interface.
from tkinter import *#Imports the package tkinter for the user interface.
from tkinter import ttk#Imports the ttk module, used in the Food/Drink menus.
root = Tk()
tree = ttk.Treeview(root)
def Load_Main_Menu():#Loads the main menu (Food, Drink, Exit, etc.)
#Positions the buttons by setting topFrame as the top (re:First), bottomFrame as
#bottom (re: Last) and then the other buttons fill the space between
Top_Frame = Frame(root)
Top_Frame.pack()
Bottom_Frame = Frame(root)
Bottom_Frame.pack(side = BOTTOM)
#This chunk of code creates the buttons, sets the text, links it to the
#function and also decides it's colour.
Menu_Food_Button = Button(Top_Frame, text = "Food", command = Food_Button, fg = 'Blue')
Menu_Stock_Button = Button(Top_Frame, text = "Stock Control", command = Stock_Control_Button, fg = 'Green')
#The code below determines which side of the parent widget packs against.
Menu_Food_Button.pack(side=LEFT)
Menu_Stock_Button.pack(side=LEFT)
root.mainloop()
def Food_Menu():
tree['columns'] = ('Price', 'Qty', 'Print Receipt')#additional columns after the default '#0'
tree.column('Price', stretch = 0, width = 100, anchor = E)#Price Column, tkinter.E aligns contents to the "east"
tree.column('Qty', stretch = 0, width = 100, anchor = E)#Quantity Column
tree.column('Print Receipt', stretch = 0, width = 100, anchor = E)#Print Receipt Column
tree.heading('#0', text = "Item")# default column responsible for tree mechanics
tree.heading('Price', text = "£")
tree.heading('Qty', text = "Quantity")
tree.heading('Print Receipt', text = "Get Receipt")
tree.insert('', 0, 'Print_Receipt', text = "Get Receipt")#
tree.insert('', 0, '_Chips_', text = "Chips", values = (4.99, 133))#Parent, text goes to '#0', values go to tree['columns']
tree.insert('_Chips_', 0, text = "Add to Order")#Child
tree.pack()
root.mainloop()
def Stock_Menu():#Loads the main menu (Food, Drink, Exit, etc.)
#Positions the buttons by setting topFrame as the top (re:First), bottomFrame as
#bottom (re: Last) and then the other buttons fill the space between
Top_Frame = Frame(root)
Top_Frame.pack()
Bottom_Frame = Frame(root)
Bottom_Frame.pack(side = BOTTOM)
#This chunk of code creates the buttons, sets the text, links it to the
#function and also decides it's colour.
Stock_Exit_Button = Button(Top_Frame, text = "Exit", command = Return_To_Main_Menu, fg = 'Green')
#The code below determines which side of the parent widget packs against.
Stock_Exit_Button.pack(side=LEFT)
root.mainloop()
def Food_Button():#This displays the food menu.
Food_Menu()
def Stock_Control_Button():#This displays the stock options
Stock_Menu()
def Return_To_Main_Menu():#Loads the main menu
Load_Main_Menu()
Load_Main_Menu()
So, if you've C&P that you'll see a window come up with two buttons, Food and Stock.
Click Food,
Click Stock,
Click Exit,
Click Stock,
Click Exit.
You should see the issue. I want to be able to close the window 'behind me' so they don't pile up because it's a bug that kind of needs to be fixed, but I don't know how.
I've looked online, as I've said, and come up with nothing.
I fixed the indentation and root.mainloop() suggestions by the other answers. If you don't need the tree to be shown anymore, you could use tree.destroy(). However, I think it's more appropriate to use tree.pack_forget() in this case as suggested by this answer here.
I added the tree.pack_forget() to your Return_To_Main_Menu() function and removed the original Load_Main_Menu() call since it would create two new Food and Stock buttons.. I removed the comments from the original post just for easier posting.
import tkinter
from tkinter import *
from tkinter import ttk
root = Tk()
tree = ttk.Treeview(root)
def Load_Main_Menu():
Top_Frame = Frame(root)
Top_Frame.pack()
Bottom_Frame = Frame(root)
Bottom_Frame.pack(side = BOTTOM)
Menu_Food_Button = Button(Top_Frame, text = "Food", command = Food_Button, fg = 'Blue')
Menu_Stock_Button = Button(Top_Frame, text = "Stock Control", command = Stock_Control_Button, fg = 'Green')
Menu_Food_Button.pack(side=LEFT)
Menu_Stock_Button.pack(side=LEFT)
root.mainloop()
def Food_Menu():
tree['columns'] = ('Price', 'Qty', 'Print Receipt')
tree.column('Price', stretch = 0, width = 100, anchor = E)
tree.column('Qty', stretch = 0, width = 100, anchor = E)
tree.column('Print Receipt', stretch = 0, width = 100, anchor = E)
tree.heading('#0', text = "Item")
tree.heading('Price', text = "£")
tree.heading('Qty', text = "Quantity")
tree.heading('Print Receipt', text = "Get Receipt")
tree.insert('', 0, 'Print_Receipt', text = "Get Receipt")
tree.insert('', 0, '_Chips_', text = "Chips", values = (4.99, 133))
tree.insert('_Chips_', 0, text = "Add to Order")#Child
tree.pack()
def Stock_Menu():
Top_Frame = Frame(root)
Top_Frame.pack()
Bottom_Frame = Frame(root)
Bottom_Frame.pack(side = BOTTOM)
Stock_Exit_Button = Button(Top_Frame, text = "Exit", command = Return_To_Main_Menu, fg = 'Green')
Stock_Exit_Button.pack(side=LEFT)
def Food_Button():
Food_Menu()
def Stock_Control_Button():
Stock_Menu()
def Return_To_Main_Menu():
tree.pack_forget()
Load_Main_Menu()
I am supposed to write a program with check buttons that allow the user to select any or all of these services. When the user clicks a button the total charges should be displayed. I already have the first portion done and finished but I need help with the second part. I can't find a calculation that works when the user clicks the buttons and the total charges are calculated and displayed within the same box. What is the correct calculation to add the selected? Here's what I have so far:
#Create the checkbutton widgets in top frame.
self.cb1 = tkinter.Checkbutton(self.top_frame, \
text = 'Oil Change-$30.00', variable = self.cb_var1)
self.cb2 = tkinter.Checkbutton(self.top_frame, \
text = 'Lube Job-$20.00', variable = self.cb_var2)
self.cb3 = tkinter.Checkbutton(self.top_frame, \
text = 'Radiator Flush-$40.00', variable = self.cb_var3)
self.cb4 = tkinter.Checkbutton(self.top_frame, \
text = 'Transmission Flush-$100.00', variable = self.cb_var4)
self.cb5 = tkinter.Checkbutton(self.top_frame, \
text = 'Inspection-$35.00', variable = self.cb_var5)
self.cb6 = tkinter.Checkbutton(self.top_frame, \
text = 'Muffler Replacement-$200.00', variable = self.cb_var6)
self.cb7 = tkinter.Checkbutton(self.top_frame, \
text = 'Tire Rotation-$20.00', variable = self.cb_var7)
#Pack the checkbuttons.
self.cb1.pack()
self.cb2.pack()
self.cb3.pack()
self.cb4.pack()
self.cb5.pack()
self.cb6.pack()
self.cb7.pack()
#Create an OK button and Quit button.
self.ok_button = tkinter.Button(self.bottom_frame, \
text = 'OK', command = self.show_choice)
self.quit_button = tkinter.Button(self.bottom_frame, \
text = 'Quit', command = self.main_window.destroy)
#Pack the buttons.
self.ok_button.pack(side = 'left')
self.quit_button.pack(side = 'left')
#Pack frame.
self.top_frame.pack()
self.bottom_frame.pack()
I am not a tkinter person but I would do it as if I was making this in wxpython and you will just have to translate it from there.
So first I would make a dictionary of all checkbox names and the price associated with it. It would look something like this:
priceCheckUp = {"Oil Change-$30.00":30, "Lube Job-$20.00":20...} #Keep going with all the rest of them
Next you would want list of all the checkboxes. I would change your code to have your checkboxes appended to a list like:
checkboxes = []
checkboxes.append(tkinter.Checkbutton(self.top_frame, \
text = 'Oil Change-$30.00', variable = self.cb_var1)) #Do that for all of them
So now that you have a list, you can use a for loop like such after the user presses the button:
total = 0
for i in checkboxes:
if i.isChecked():
total = total + priceCheckUp[i.GetLabel()]
print total #Or display the data however you want
The above code was done for wxPython Checkboxes so you will have to do some translating.
Here's an implementation of the essence of what I said in my comment. Although it's based on the code in your answer, I've added a lot of supporting code so I could test it. One significant change I made was to put all the Checkbutton widgets and their associated control variables into lists instead of explicitly giving each one a unique name — which was getting out-of-hand you have so many of them.
That said, the checking of the state of each Checkbutton and adding up the costs of checked items in shown in the show_choice() method.
import tkinter
# Table of services containing their names and costs.
SERVICES = [('Oil Change', 30.00),
('Lube Job', 20.00),
('Radiator Flush', 40.00),
('Transmission Flush', 100.00),
('Inspection', 35.00),
('Muffler Replacement', 200.00),
('Tire Rotation', 20.00)]
class MyApp(tkinter.Frame):
def __init__(self, master=None):
tkinter.Frame.__init__(self, master)
self.pack()
self.main_window = root
self.top_frame = tkinter.Frame(self)
self.bottom_frame = tkinter.Frame(self)
# Create list of control variables to query state of CheckButtons.
self.cb_vars = [tkinter.IntVar() for _ in range(len(SERVICES))]
# Create another list to hold a corresponding Checkbuttons.
self.cbs = [
tkinter.Checkbutton(
self.top_frame,
text='{}-${:.2f}'.format(SERVICES[i][0], SERVICES[i][1]),
variable=self.cb_vars[i])
for i in range(len(self.cb_vars))
]
# Pack the Checkbuttons.
for i in range(len(self.cbs)):
self.cbs[i].pack()
#Create an OK button and Quit button.
self.ok_button = tkinter.Button(self.bottom_frame,
text='OK', command=self.show_choice)
self.quit_button = tkinter.Button(self.bottom_frame,
text='Quit', command=self.main_window.destroy)
#Pack the buttons.
self.ok_button.pack(side = 'left')
self.quit_button.pack(side = 'left')
#Pack frames.
self.top_frame.pack()
self.bottom_frame.pack()
def show_choice(self):
popup_window = tkinter.Toplevel()
label_frame = tkinter.LabelFrame(popup_window, text='Total Charges')
label_frame.pack()
# Add up the cost of all the items which are checked.
total = sum(SERVICES[i][1] for i in range(len(self.cb_vars))
if self.cb_vars[i].get())
tkinter.Label(label_frame, text='${:.2f}'.format(total)).pack()
# Enter a local mainloop and wait for window to be closed by user.
root.wait_window(popup_window)
root = tkinter.Tk()
app = MyApp(root)
app.master.title('Cost Calculator')
app.mainloop()
Here's a screenshot of it running:
I want to present several questions, one after another. The first question is shown as I like, with the cursor set in the entry field. Then I destroy the window and call the function again to create a new window. This time the window is not shown in the front and therefore I first have to click on the screen in order to have the cursor set to the entry field. Also the escape key does not work until I click on the screen to bring the window to the top. I'd be very happy for your help!
Thank you in advance!
Here's my code:
from Tkinter import *
def text_input_restricted(fn,question, nr_letters, limit, len_min, len_max,keys, justify):
class MyApp():
def validate(root, S):
return all(c in keys for c in S)
def __init__(self, q= None):
#save response after "next"-button has been clicked
def okClicked():
lines = e.get()
if len_min < len(lines) < len_max:
lines = unicode(lines).encode('utf-8')
datFile = open(fn, "a")
datFile.write(" '%s'"%(lines))
datFile.close()
self.root.destroy()
self.root = Tk()
vcmd = (self.root.register(self.validate), '%S')
#quit if escape-key has been pressed
self.root.bind('<Escape>', lambda q: quit())
#colors
color = '#%02x%02x%02x' % (200, 200, 200)
self.root.configure(bg=color)
#set window size to screen size
RWidth=MAXX
RHeight=MAXY
self.root.geometry(("%dx%d")%(RWidth,RHeight))
#remove buttons (cross, minimize, maximize)
self.root.overrideredirect(1)
#remove title
self.root.title("")
#item
labelWidget = Label(self.root,text=question, font=("Arial", int(0.02*MAXX)), bd=5, bg=color, justify="center")
labelWidget.place(x=0, y=RHeight/40,width=RWidth)
#"next"-button
ok_width = RWidth/15
ok_height = RWidth/15
okWidget = Button(self.root, text= "next", command = okClicked, font=("Arial",int(0.015*MAXX)), bd=5, justify="center")
okWidget.place(x=RWidth/2-ok_width/2,y=13*RHeight/40, width=ok_width,height=ok_height)
def callback(sv):
c = sv.get()[0:limit]
sv.set(c)
sv = StringVar()
width=nr_letters * int(0.02*MAXX)*1.3
sv.trace("w", lambda name, index, mode, sv=sv: callback(sv))
e = Entry(self.root, textvariable=sv,font=("Arial", int(0.02*MAXX)),justify=justify,validate="key", validatecommand=vcmd)
e.place(x=RWidth/2-width/2, y=9*RHeight/40, width=width)
#show cursor
e.focus_set()
self.root.mainloop()
MyApp()
MAXX=1366
MAXY=768
fn = "D:/test.dat"
text_input_restricted(fn = fn, question=u"f for female, m for male", nr_letters=1, limit =1, len_min =0, len_max=2, keys = 'fm', justify="center")
text_input_restricted(fn = fn, question="How old are you?", nr_letters=2,limit=2, len_min = 1, len_max = 3, keys = '1234567890',justify="center")
In Tk you use the raise command to bring a window to the front of the Z-order. However, raise is a keyword in Python so this has been renamed to lift. Provided your application is still the foreground application you can call the lift() method on a toplevel widget. If the application is not the foreground application then this will raise the window but only above other windows from the same application. On Windows this causes the taskbar icon for your application to start flashing.
You might do better to destroy the contents of the toplevel and replace them. Or even better - create a number of frames holding each 'page' of your application and toggle the visibility of each frame by packing and pack_forgetting (or grid and grid forget). This will avoid loosing the focus completely - you can just set the focus onto the first widget of each frame as you make it visible.