So I'm attempting to make a program with tkinter, and so far, things have gone somewhat as hoped, and I nearly achieved what I wanted.
But I've got a problem with destroying labels.
from tkinter import *
root = Tk()
root.geometry("500x500")
def controleerAntwoord(gekozenHeld, submit, eersteHintButton):
antwoord = entry.get()
if antwoord == gekozenHeld:
submit.destroy()
eersteHintButton.destroy()
eersteHint("destroy", button)
startspel()
def eersteHint(superheldHint, button):
hintTextLabel = Label(root, text = "First hint: ")
hintLabel = Label(root, text = superheldHint)
if superheldHint != "destroy":
hintTextLabel.pack()
hintLabel.pack()
button.destroy()
if superheldHint == "destroy":
hintTextLabel.destroy()
hintLabel.destroy()
def startspel():
entry.delete(0, 'end')
gekozenHeld = "test"
superheldHint1 = 'hey'
eersteHintButton = Button(root, text = "Give First Hint", command = lambda: eersteHint(superheldHint1, eersteHintButton))
submit = Button(root, text = "Submit Answer",foreground = "blue", command = lambda: controleerAntwoord(gekozenHeld, submit, eersteHintButton))
eersteHintButton.pack(side = BOTTOM)
entry.pack(side = BOTTOM)
submit.pack(side = BOTTOM, pady = 20)
def start_up():
name = entry.get().strip()
if name != "":
button.destroy()
giveName.destroy()
startspel()
giveName = Label(root, text="Insert your name: ")
entry = Entry(root)
button = Button(root, text="Enter", command=start_up)
entry.pack()
button.pack()
root.mainloop()
This is my current code so far, I know it looks big, but a lot of it can be ignored for this question.
As to how the program works, you enter your name and get taken to the next window.
There you can press the submit button and enter some text, as well as asking for a hint.
When you press the hint button, you get some text on the screen, and when you submit the correct answer, which in this case, is "test", the text should disappear. But it does not.
Any ideas on what I'm doing wrong?
The problem is that you're using a local variable, but expecting that local variable to somehow be remembered the second time you call the function. All your code does is create a label and then immediately destroy the one it just created. If you want it to destroy the one created earlier, you'll have to store that in a global variable.
Related
I am new to programming and Tkinter. I want to DISABLED textbox when checkbox is pressed and open it NORMAL when box is not ticked. Here is my code:
from tkinter import *
root = Tk()
def lock_fields():
if check == True:
data.configure(state=DISABLED)
if check == False:
data.configure(state=NORMAL)
check = BooleanVar()
open_for_edit = Checkbutton(root, text="check the box for editing", variable=check,
onvalue=True, offvalue=False, command=lambda: lock_fields())
open_for_edit.pack()
check = check.get()
data = Text(root)
data.insert(END, "I would like to be able to edit this text only when checkbox is checked.")
data.pack()
root.mainloop()
It seems that for some reason the check-variable is always False when it enters to lock_fields function. I tried passing check argument to the method.
You're pretty close, only thing is that the check.get() line must be in the function. Also you don't need the lambda. Try this:
from tkinter import *
root = Tk()
def lock_fields():
if check.get():
data.configure(state=DISABLED)
else:
data.configure(state=NORMAL)
check = BooleanVar()
open_for_edit = Checkbutton(root, text="check the box for editing", variable=check, onvalue=True, offvalue=False, command=lock_fields)
open_for_edit.pack()
data = Text(root)
data.insert(END, "I would like to be able to edit this text only when checkbox is checked.")
data.pack()
root.mainloop()
I just want that when I type my name inside the entry box then appears in another entry with some add text. The idea is type in the entry below and after that it showed in the big entry.I was looking for this solution, but just found place in Label. I don't want in Label. The window is more big, must drag to show the entry. There's is a picture that i use in this script:
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
cat = Entry(root)
cat.place(x=48, y=25, width= 350, height=140)
user = Entry(root)
user.place(x=75, y=550)
btn = Button(root, text='START')
btn.place(x=220, y=410)
root.mainloop()
#
Ok, It works the way you told me,thank you!
But now i'm facing another problem.
The problem is when i insert the function of the game in the second window. I tested in one window and it works, but when i place the function in the second window gives an error when i press the "Start" button:
'''user_try = int(txt.get())
NameError: name 'txt' is not defined'''
When i press reset button gives another error:
'''user_try = int(txt.get())
NameError: name 'txt' is not defined'''
So i know that is missing definition, but i don't know how to make a reference for this command that it's in the second window. Like i said running with just one window the program works.
Maybe i should make using class, i don't know, but i wish to make this way that i started. However if there's no other way to do as i'm doing, let's go.
I just simplify the script here, actualy the main script is more bigger, so my idea is when open the program, there is a window and the user read the instructions about the game and proceed open the second window. The window have pictures and some hidden buttons in the next picture, so there will be an interactivity with the environment.
The guess number is just the beggining. After that there will be new challeges.
I'm very excited doing this, but i'm stuck in this point. The part one i finished, the pictures, the hidden buttons it's exacly the way i want, but the challenge stops here in this problem.
from tkinter import *
from PIL import Image, ImageTk, ImageSequence
import random
from tkinter import messagebox
pc = random.randint(1,10)
def reset():
global pc
pc = random.randint(1,10)
cat['text'] = 'Ok! Lets Try Again!'
def openwin2():
win1.withdraw()
win2 = Toplevel()
win2.geometry('350x300+180+100')
win2.title('second window')
txt = Entry(win2)
txt.place(x=10,y=10)
cat = Label(win2,wraplength=300)
cat.place(x=10,y=50)
cat.config(text='Hi! I Am thinking a number between 1 and 10.')
btn = Button(win2,text='start',command=check)
btn.place(x=30, y=150)
btn2 = Button(win2, text='reset', command=reset)
btn2.place(x=110,y=150)
win2.mainloop()
def check():
user_try = int(txt.get())
if user_try < pc:
msg = 'Hmmmm... the number, which I thought of, is greater than this.'
elif user_try > pc:
msg = 'How about trying a smaller number ?!'
elif user_try == pc:
msg = 'Well Done! You guessed! It was %s the number!' % user_try
else:
msg = 'Something Went Wrong...'
cat['text'] = msg
win1 = Tk()
win1.title('First Window')
win1.geometry('350x300')
user = Label(win1,text='first window')
user.place(x=10,y=10)
btn1 = Button(win1,text='Open Window 2', command=openwin2)
btn1.place(x=10,y=50)
win1.mainloop()
There are multiple ways to do this in tkinter, here's a rework of your code using StringVar objects set to the textvariable properties of your Entry objects:
import tkinter as tk
def doit():
out_string.set("Hello " + in_string.get())
root = tk.Tk()
in_string = tk.StringVar()
out_string = tk.StringVar()
cat = tk.Entry(root, textvariable=in_string)
cat.place(x=20, y=25, width=100)
user = tk.Entry(root, textvariable=out_string)
user.place(x=20, y=75)
btn = tk.Button(root, text='START', command=doit)
btn.place(x=20, y=150)
root.mainloop()
Per #Mike-SMT, here's a different approach using Entry.get() and Entry.insert(). It augments the text when the user clicks the button:
import tkinter as tk
def doit():
user.insert(tk.END, cat.get())
root = tk.Tk()
cat = tk.Entry(root)
cat.place(x=20, y=25, width=100)
user = tk.Entry(root)
user.place(x=20, y=75)
user.insert(0, "Hello ")
btn = tk.Button(root, text='START', command=doit)
btn.place(x=20, y=150)
root.mainloop()
However, you'll see that subsequent button clicks keep appending the text. When working with Entry.insert(), you need to work with Entry.delete() and/or other Entry methods to properly manipulate the text.
I'M SO CONFUSED
Keep in mind that I'm a beginner at programming/python so if my code is unorganized or badly worded, ignore it, I'm getting better lol
I'm just playing with tkinter and I'm trying to get a login screen that has a checkbox that toggles the visibility of the password. I just don't understand anymore. The "show" argument won't change based on the variable it was assigned and I don't know why.
showPassword = IntVar()
show = None
def apply():
print(showPassword.get())
sspass = showPassword.get()
print(type(sspass))
if sspass == 1:
show = None
elif sspass == 0:
show = "*"
spB = Checkbutton(root, text="Toggle Show Password", variable=showPassword).grid(row=10, column=1)
applyButton = Button(root, text="Apply", command=apply).grid(column=1, row=5)
Password = entry(root, show=show)
I have arranged a snippet of code (that is not perfect for you to follow but...) based on yours that at least works for you to progress. Your code is incomplete I suppose, it has also some errors. You have to configure the show parameter in the widget. Changing your show var won't do anything to the widget.
You'll have to use the form widget['show'] = somevalue. Or the .configurewidget method. For both you'll need a widget reference. If you grid a widget in the same line you create it, grid will return nothing so you loose it. Break that in two steps and keep the reference for the widget at creation (first step). entry is actually called Entry. These where the most prominet errors I saw.
from tkinter import Button, Checkbutton, Entry, Tk, IntVar
root = Tk()
showPassword = IntVar()
show = None
def apply():
print(showPassword.get())
sspass = showPassword.get()
print(type(sspass))
if sspass == 1:
Password['show'] = ""
elif sspass == 0:
Password['show'] = "*"
Password.update()
spB = Checkbutton(root, text="Show Password", variable=showPassword).grid(row=10, column=1)
applyButton = Button(root, text="Apply", command=apply).grid(column=1, row=5)
Password = Entry(root, show=show)
Password.grid(row=3, column=1)
root.mainloop()
This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 5 years ago.
I'm trying to make my program change the text based on a variable selected in the dropdown menu, but the button to activate the command doesn't seem to be working. From what I can see, the select function run's once the program is loaded and then never again, regardless of when I click the button.
from Tkinter import *
class App:
def __init__(self, root):
self.title = Label(root, text="Choose a food: ",
justify = LEFT, padx = 20).pack()
self.label = Label(root, text = "Please select a food.")
self.label.pack()
self.var = StringVar()
self.var.set("Apple")
food = ["Apple", "Banana", "Pear"]
option = apply(OptionMenu, (root, self.var) + tuple(food))
option.pack()
button = Button(root, text = "Choose", command=self.select())
button.pack()
def select(self):
selection = "You selected the food: " + self.var.get()
print(self.var.get()) #debug message
self.label.config(text = selection)
if __name__ == '__main__':
root = Tk()
app = App(root)
root.mainloop()
I'm a beginner on Tkinter, and I'm trying to figure out the basics before I go into making my full app. Thanks in advance :)
Try changing button = Button(root, text = "Choose", command=self.select()) to button = Button(root, text = "Choose", command=self.select). Note the removed parentheses after self.select. This way, the method only gets referenced and not actually executed until you press the button.
Your main issue is you don't need the parentheses when setting command=self.food():
button = Button(root, text="Choose", command=self.select)
As a side-note, the way you generate your OptionMenu is slightly unusual. You can use the following instead, which is more consistent with the rest of your code:
option = OptionMenu(root, self.var, *food)
The command parameter documentation as per tkinterbook.
(A function or method that is called when the button is pressed. The callback can be a function, bound method, or any other callable Python object. If this option is not used, nothing will happen when the user presses the button.)
*****************************modified code*******************************
from Tkinter import *
class App:
def __init__(self, root):
self.title = Label(root, text="Choose a food: ",
justify = LEFT, padx = 20).pack()
self.label = Label(root, text = "Please select a food.")
self.label.pack()
self.var = StringVar()
self.var.set("Apple")
food = ["Apple", "Banana", "Pear"]
option = apply(OptionMenu, (root, self.var) + tuple(food))
option.pack()
button = Button(root, text = "Choose", command=self.select)
#use function name instead of aclling the function
button.pack()
def select(self):
selection = "You selected the food: " + self.var.get()
print(selection) #debug message
self.label.config(text = selection)
if __name__ == '__main__':
root = Tk()
app = App(root)
root.mainloop()
#Last one Looses (II)
from tkinter import *
from tkinter import ttk
root = Tk()
#window
root.title("Last one Looses Mark II")
#Counters Entry
counters = StringVar()
countersL = Label(root, text = "How many counters do you want to play with (10-50)")
countersL.pack(side = LEFT)
countersE = Entry(root, textvariable = counters, bd = 5)
countersE.pack(side = RIGHT)
#Function to process this
def countersinput():
no_counters = int(input(counters.get()))
no_counters = int(input(counters.get()))
#Submit Button
countersB = Button(root, text = "Submit", command = countersinput)
countersB.pack(side = BOTTOM)
#Making sure the counters are between 10-50
while no_counters > 50 or no_counters < 10:
Error = Message(root, text="You need to pick between 10 and 50 counters...")
Error.pack()
counters = StringVar()
countersL = Label(root, text = "How many counters do you want to play with (10-50)")
countersL.pack(side = LEFT)
countersE = Entry(root, textvariable = counters, bd = 5)
countersE.pack(side = RIGHT)
def countersinput():
no_counters = int(input(counters.get()))
countersB = Button(root, text = "Submit", command = countersinput)
countersB.pack(side = BOTTOM)
#Sucess Message
Sucess = Message(root, text=("You are playing with",no_counters,"counters"))
root.mainloop()
Whenever I run it in IDLE the tkinter window does not come up and when I run it into the command line (python one...) it displays the window but with no "submit" button.
I'm really confused please help!
First off, do you realize that your GUI program is asking for input from the command line, and that you're doing that before creating the submit button? That's the reason why the submit button is not showing up. If you're writing a GUI program, you should not be trying to read input from the command line.
If you enter a number between 10 and 50 from the terminal, your code should display a window. However, if you enter a number outside that range, nothing will ever show because of the while no_counters ... loop. That loop will run infinitely, preventing any other interaction with the GUI, and preventing any other widgets from showing up.