I want to use Tkinter in loop and not sure how to do that. I want to display an "Correct" message when certain condition is met using Tkinter. for ex if the value is <=20 then it should display message otherwise show " not correct". I am only able to create a code to display message but do not know how to use this message with the condition. Below is my code :
import tkinter
from tkinter import messagebox
# This code is to hide the main tkinter window
root = tkinter.Tk()
root.withdraw()
# Message Box
messagebox.showinfo(" Correct!!")
My solution will going to have an example inspired by your explanation about what you are trying to do.
Well your code would not do anything like you want to. So I am writing a code which will take a number input from a user. If the number is greater than 20 then it would display "Correct" else it would display "Incorrect".
Here is the code I wrote:
import tkinter
from tkinter import messagebox
root = tkinter.Tk()
question = tkinter.Label(root, text="Enter any number")
question.place(x=5, y=5)
question_entry = tkinter.Entry(root)
question_entry.place(x=5, y=50)
def check():
x = 20
y = int(question_entry.get())
if y >= x:
messagebox.showinfo(title="Check", message="Correct!")
elif y < x:
messagebox.showinfo(title="Check", message="Incorrect!")
else:
messagebox.showerror(title="Check", message="Some unexpected error occured!")
submit_button = tkinter.Button(root, text="Start", command=check)
submit_button.place(x=5, y=100)
root.mainloop()
Explanation:
Using label to display "Enter any number"
I have used Entry widget to take input from the user. And to retrieve it I have used int(question_entry.get()). Also I have added int() to make the entry an integer as the default entry is str.
The function check is created so as to run the program when the button is pressed. I have used command=check attribute run the program when it is clicked.
showinfo is being used to send a message in a separate window. showerror is created in else condition just in case some error comes up. (less likely to happen)
I have removed the root.withdraw() statement as this program can be used multiple time. But just in case if you want to hide the window you can add root.withdraw() just above the line x=20 and it would work just fine. (I tried is already)
It there is still something that I failed to explain, please feel free to ask in the comments. :)
Related
I know how to change a label's color with a command attached to a button, but I want to do it programmatically, based on a variable's value.
If an error message is sent to the build_window function, I want to display the error message on a label with a red background, and if a non-error message is sent, no message is to be displayed and no color changes are expected.
In my code, I call the function to build a tkinter window two times.
The first time, I pass it a non-error message, the second time, an error message.
My code works for displaying the error message when expected, the problem is only with changing the background color of the error message label.
If I un-comment the l1.config(bg="red") command shown, I get this error when passing an error message to build_window():
UnboundLocalError: local variable 'l1' referenced before assignment
on the l1.config(bg="red") command.
If I move the entire if structure to just before mainloop(), I get this error even when passing the non-error message:
UnboundLocalError: local variable 'error_message' referenced before assignment
on the l1=Label(root,text = error_message) command.
If I add global l1 and global error_message to build_window(), the error I get is this:
tkinter.TclError: invalid command name ".!label"
I also tried just initially defining the label with bg="red", hoping that when I send a zero-length string, it would still be gray, but it displays a bit of red in the middle of the l1 label.
I've been writing simple python for a while, but I'm new to GUI apps and tkinter just confuses me every time I try something.
I've searched for a solution but could not find anything addressing changing a window without using a command attached to a button.
Any advice or clarification would be greatly appreciated!
from tkinter import Tk, IntVar, Label, mainloop, Button
def build_window(incoming_error_message) :
if incoming_error_message == "initial value" :
error_message = ""
else :
#l1.config(bg="red")
error_message = incoming_error_message
def quitHandler():
root.destroy()
root = Tk()
l1=Label(root,text = error_message)
l1.grid(row=0,column=0)
quitButton = Button(root, text="To end, click here",command=quitHandler)
quitButton.grid(row=1,column=0)
mainloop()
def call_build_window() :
build_window("initial value")
build_window("Error!")
call_build_window()
One option is to place the label creation within the condition and reorder the surrounding code a little bit. I also replaced grid by pack and skipped keeping names for variables which are actually constants, all that changes were made to keep the code small:
from tkinter import Tk, Label, mainloop, Button
def build_window(error_message):
root = Tk()
if error_message == "initial value":
Label(root, text="").pack()
else:
Label(root, text=error_message, bg="red").pack()
def quitHandler():
root.destroy()
Button(root, text="To end, click here", command=quitHandler).pack()
mainloop()
def call_build_window():
build_window("initial value")
build_window("Error!")
call_build_window()
This of course is a small case study and shouldn't be used to build on it.
I think it should be reworked so that there is a maybe function that takes the indicator if the message is as a second argument with the text always being displayed. All that would be much easier in a more object-oriented approach. (Also remember that Tk() is normally called only once and secondary top-level windows are created via Toplevel(), see Python - Tkinter - invisible text in ttk.Entry in sub window or tkinter: Open a new window with a button prompt. )
By using tkinter.ttk it's also possible to change the widget's style at runtime, see the answer to Changing ttk widget text color for an example.
So, essentially what is going on is I made a password manager that had a password generation part to it, I moved it to a windowed Tkinter program for ease of use. I got everything down except for the check box, so at first when the function was called it would give me the error that alphabet had empty length so I set alphabet equal to the list with special characters. After that I tried them with while loops, same result. (this whole code is a function inside the program that only gets ran when a button is pressed) I know I could probably fix this issue with the init but I was hoping if anyone knew an easier way without rewriting too much. Here is the edit to make the code simplified. I used it with a while loop, and got the same result as the if statement. I get the error that a is not defined in this situation.
from tkinter import *
import random
def cbox_var():
while cbox_1 == True:
a = 10
while cbox_1 == False:
a = 20
print(a)
main = Tk()
cbox_1 = Checkbutton(main, text="yes or no")
cbox_1.pack()
testbutton = Button(main,text="Test", command=cbox_var)
testbutton.pack()
main.mainloop()
To get the value of a checkbutton you must assign one of the special tkinter variables to it. You can then get the value by calling the get method on the variable.
Example:
import tkinter as tk
def cbox_var():
checked = cbox_variable.get()
print("Checked?", checked)
main = tk.Tk()
cbox_variable = tk.BooleanVar()
cbox_1 = tk.Checkbutton(main, variable=cbox_variable, text="yes or no")
cbox_1.pack()
testbutton = tk.Button(main,text="Test", command=cbox_var)
testbutton.pack()
main.mainloop()
I have some pretty simple code right now that I am having issues with.
root = Tk()
label1 = Label(root, text ="Enter String:")
userInputString = Entry(root)
label1.pack()
userInputString.pack()
submit = Button(root,text = "Submit", command = root.destroy)
submit.pack(side =BOTTOM)
root.mainloop()
print(userInputString)
When I run the code everything operates as I would expect except
print(userInputString)
for an input asdf in the Entry print will return something like 0.9355325
But it will never be the same value back to back always random.
I am using python 3.5 and Eclipse Neon on a Windows 7 Machine.
Ultimately the goal is to accept a string from the user in the box that pops up and then be able to use that value as string later on. For example, it might be a file path that needs to be modified or opened.
Is Entry not the correct widget I should be using for this? Is there something inherently wrong with the code here? I am new to python and don't have a lot of strong programming experience so I am not even certain that this is set up right to receive a string.
Thanks in advance if anyone has any ideas.
There are two things wrong with your print statement. First, you print the widget, not the text in the widget. print(widget) prints str(widget), which is the tk pathname of the widget. The '.' represents the root window. The integer that follows is a number that tkinter assigned as the name of the widget. In current 3.6, it would instead be 'entry', so you would see ".entry".
Second, you try to print the widget text after you destroy the widget. After root.destroy, the python tkinter wrapper still exists, but the tk widget that it wrapped is gone. The following works on 3.6, Win10.
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text="Enter String:")
entry = tk.Entry(root)
def print_entry(event=None):
print(entry.get())
entry.bind('<Key-Return>', print_entry)
entry.focus_set()
submit = tk.Button(root, text="Submit", command=print_entry)
label.pack()
entry.pack()
submit.pack()
root.mainloop()
Bonus 1: I set the focus to the entry box so one can start typing without tabbing to the box or clicking on it.
Bonus 2: I bound the key to the submit function so one can submit without using the mouse. Note that the command then requires an 'event' parameter, but it must default to None to use it with the button.
The NMT Reference, which I use constantly, is fairly complete and mostly correct.
I am using mac OS X python. I'm working with GUI right now and is making a simple window with three buttons. I'm trying to configure some buttons to make them do something but it is not working. Can anyone tell me what the problem is? So far I have a little window with three buttons. I wrote the code:
win=Tk()
f=Frame(win)
b1=Button(f,text="one")
b2=Button(f,text"two")
f.pack()
def but1() : print "Button one was pushed"
b1.configure(command=but1)
I am getting the error message invalid syntax for that.
Your program needs to call root.mainloop() on the last line. You also have the problem that you aren't calling pack or grid on the buttons. After adding the call to mainloop() you'll just see any empty window until you call pack or grid on the buttons.
The only thing that I see wrong with your code is that you forgot to include = when you define b2. Running exactly what you have written will raise a Syntax Error.
from Tkinter import *
win = Tk()
f = Frame(win)
b1 = Button(f, text="one")
b2 = Button(f, text="two") # Don't forget the equals sign.
f.pack()
def but1():
print "Button one was pushed"
b1.configure(command=but1)
I am trying to create a simple popup text entry for the user in which a user enters a text and hits submit (a button). Upon clicking submit, I want the popup entry box to close off and continue on with the rest of the code. Following is a sample code for display that I borrowed from an old post here:
from Tkinter import *
root = Tk()
nameLabel = Label(root, text="Name")
ent = Entry(root, bd=5)
def getName():
print ent.get()
submit = Button(root, text ="Submit", command = getName)
nameLabel.pack()
ent.pack()
submit.pack(side = BOTTOM)
root.mainloop()
print "Rest of the code goes here"
I don't have much experience with Tkinter so I am not sure where and how exactly to call the appropriate functions for closing the entry box after the user hits 'Submit'. My guess is it would have to be inside the getName() function?
If I understand you correctly, then all you need to do is call the root window's destroy method at the end of the getName function:
def getName():
print ent.get()
root.destroy()
Doing so is equivalent to manually clicking the X button in the corner of the window.
Alternate method:
since there isn't much to your popup you could also eliminate several lines of code in your GUI, save some CPU and get pretty much the same output with this:
submitvariablename=raw_input('Please enter a Name')
same functionality and much faster, cleaner.
Just a thought.