im trying to make some code, so that when you type your name into the input box and hit the ok button, your name is then retrieved, and used as the text in a picture, my code is below.
from Tkinter import *
c = Canvas(width=500, height=500, bg='white')
c.pack(expand=YES, fill=BOTH)
master = Tk()
var = StringVar(master)
var.set("one") # initial value
option = OptionMenu(master, var, "one", "two", "three", "four")
option.pack()
#
def ok():
print "value is", var.get()
master.quit()
user = var.get() ##### this is what im struggling with
button = Button(master, text="OK", command=ok)
user = var.get()
c.create_text(200,470,text="by "+user, anchor=N, justify=CENTER) # credits
mainloop()
I think I know what you want to do? I have made some code which you enter your name into an entry box, when you hit ok your name is made into a label on the same tk window as the entry box.
Here is the code:
from Tkinter import *
master = Tk()
label = Label(text='please enter you name:')
label.pack()
entry = Entry()
entry.pack()
def ok():
type = ('Times', 20)
name = entry.get()
Label(text = name, font = type).pack()
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
give it a try and tell me if this is what you wanted or not!
Related
I have created a simple text box and want to take the text from it when i click on a button, but for some reason it doesn't work. I tried using a global variable but it still doesn't work.
Here is what i have written sofar:
t = Text(r, height=20, width=40)
t.pack()
def myClick():
myLabel= Label(r,text= "Sent!")
global input
input = t.get("1.0", 'end-1c')
myLabel.pack()
myButton = Button(r, text="Send ", command=myClick)
myButton.pack()
print(input)
r.mainloop()
I think you are using too many arguments in the .get() and the widget type has to be Entry and you really should define your variable before everything else. Here is my suggestion for your code:
from tkinter import *
r = Tk()
t = Entry(r, width=40)
t.pack()
def myClick():
global input
input = t.get()
myLabel= Label(r,text= input)
myLabel.pack()
myButton = Button(r, text="Send ", command=myClick)
myButton.pack()
print(input)
r.mainloop()
I'm working on a python assignment and this is where I got so far. I'm stuck and cannot execute the application. I'm making a calculator that scores the average and gives a grade letter. I was looking into my professor's video and there was "import tkinter.messagebox as tkm" but Im not sure how to implement this in the code.
this is my code:
import tkinter as tk
import tkinter.messagebox as tkm
window = tk.Tk()
window.geometry('400x400')
window.title("Exam Calculator")
window = tk.Tk()
window.geometry('300x300')
def calculate():
score1 = float(entry1.get())
score2 = float(entry2.get())
score3 = float(entry3.get())
avg = (score1 + score2 + score3)/3
if(avg>=90):
lettergrade= "A"
elif(avg>=80 and avg<=89):
lettergrade = "B"
elif(avg>=70 and avg<=79):
lettergrade= "C"
elif(avg>=60 and avg<=69):
lettergrade = "D"
else:
lettergrade = "F"
label1 = tk.Label(window, text='Test 1')
label1.pack()
entry1 = tk.Entry(window)
entry1.pack()
label2 = tk.Label(window, text='Test 2')
label2.pack()
entry2 = tk.Entry(window)
entry2.pack()
label3 = tk.Label(window, text='Test 3')
label3.pack()
entry3 = tk.Entry(window)
entry3.pack()
button2 = tk.Button(window, text="Calculate",
command=calculate)
Button1 = tk.Button(window, text="quit",
command=window.destroy)
messagebox can help to create fast small message windows.
The usage is very simple, just implement this in your code:
from tkinter import messagebox
In you case:
from tkinter import messagebox as tkm
Then:
messagebox.function(title,message,options)
In your case:
tkm.function(title,message,options)
The functions are:
showinfo(): for showing some relevant informations.
showwarning(): for displaying a warning to the user.
showerror(): for displaying an error message.
askquestion(): for asking a yes/no question to the user.
askokcancel(): confirm the user’s action regarding some application
activity.
askyesno(): for asking a yes/no question about a user action.
askretrycancel(): for asking the user about doing a specific task again.
The options are:
default: this option is used to specify the default button like
ABORT, RETRY, or IGNORE in the message box.
parent: this option is used to specify the window on top of which
the message box is to be displayed.
The code needs just some improvements:
pack() the two buttons (as to display them)
add window.mainloop() at the end of your code (this is why is does not start)
There are multiple problems in your code. First, you define window two times. The second time, you just override your frist instance of window, so just leave that out.
Then you are not packing your Buttons, which means they will not be shown in your window. Lastly, you are missing the most important part of your Tkinter Application, which is to start the applications mainloop, which makes the window pop up and tells Tkinter to start listening for your mouse and keyboard interaction with the window and do something with it. This is called an event loop and is the main component of every graphical user interface. You start the eventloop by calling .mainloop() on your instance of tk.Tk, which is your window variable.
Lastly, it is unclear from your text what you actually want to do with the Messagebox.
I assume that you want to use the message box to display the result of your calculate function, since right now it doesn't do anything.
import tkinter as tk
import tkinter.messagebox as tkm
window = tk.Tk()
window.geometry('400x400')
window.title("Exam Calculator")
def calculate():
score1 = float(entry1.get())
score2 = float(entry2.get())
score3 = float(entry3.get())
avg = (score1 + score2 + score3)/3
if(avg>=90):
lettergrade= "A"
elif(avg>=80 and avg<=89):
lettergrade = "B"
elif(avg>=70 and avg<=79):
lettergrade= "C"
elif(avg>=60 and avg<=69):
lettergrade = "D"
else:
lettergrade = "F"
message = 'Your result is ' + lettergrade
tkm.showinfo(title='Result', message=message)
label1 = tk.Label(window, text='Test 1')
label1.pack()
entry1 = tk.Entry(window)
entry1.pack()
label2 = tk.Label(window, text='Test 2')
label2.pack()
entry2 = tk.Entry(window)
entry2.pack()
label3 = tk.Label(window, text='Test 3')
label3.pack()
entry3 = tk.Entry(window)
entry3.pack()
button2 = tk.Button(window, text="Calculate",
command=calculate)
button2.pack()
Button1 = tk.Button(window, text="quit",
command=window.destroy)
Button1.pack()
window.mainloop()
So over here I am trying to make a little python-tkinter program which will store your passwords of your apps in files. However, when I try to make the second screen open, I get this error:
TypeError: 'Toplevel' object is not callable
Here is the code:
from tkinter import *
from tkinter import messagebox
import os
def screen2():
global screen2
screen2 = Toplevel(root)
screen2.title("Main Page")
screen2.geometry("260x230")
screen2.resizable("False","False")
Label(screen2, text="hello").pack()
def check_code():
code_requestget = code_request.get()
print(code_requestget)
if code_requestget == code:
screen2()
else:
messagebox.showwarning("Error", "Code is incorrect")
def mainscreen():
global root
global code
global code_request
code = "1234"
root = Tk()
root.title("Passwords")
root.geometry("260x230")
root.resizable("False","False")
code_request = StringVar()
label1 = Label(root, text="Welcome - Enter Code", width="40", height="3", background="SpringGreen3")
label1.pack()
Label(text="").pack()
enter_code = Entry(root, width="20", textvariable=code_request)
enter_code.pack()
Label(text="").pack()
continue_button = Button(root, text="Continue", width="16", command=check_code)
continue_button.pack()
root.mainloop()
mainscreen()
Unrelated to your question, but seeing your window names makes me think you don't want to use Toplevel at all. That's only needed when you want 2 active windows, but I suspect you want to use one window just to check the password, then close it and open a second, "main" window, right? If so you need to reconfigure the root window instead of using Toplevel to open a new window. Like this:
from tkinter import *
from tkinter import messagebox
import os
def screen2():
frame1.destroy() # remove all the pw check stuff
root.title("Main Page") # rename window
Label(root, text="hello").pack()
def check_code():
code_requestget = code_request.get()
print(code_requestget)
if code_requestget == code:
screen2()
else:
messagebox.showwarning("Error", "Code is incorrect")
def mainscreen():
global root, code, code_request, frame1
code = "1234"
root = Tk()
root.title("Passwords")
root.geometry("260x230")
root.resizable("False","False")
frame1 = Frame(root) # create a Frame to hold pw check components
frame1.pack()
code_request = StringVar()
label1 = Label(frame1, text="Welcome - Enter Code", width="40", height="3", background="SpringGreen3")
label1.pack()
Label(frame1, text="").pack()
enter_code = Entry(frame1, width="20", textvariable=code_request)
enter_code.pack()
Label(frame1, text="").pack()
continue_button = Button(frame1, text="Continue", width="16", command=check_code)
continue_button.pack()
root.mainloop()
mainscreen()
if i write some thing on the textfield and press enter key on the keyboard.what i entered on the textfield display messagebox. this point get error if(format(k=event.char(13)))) : if i set the enter key code. i added full code below.
from tkinter import *
root = Tk()
root.geometry("800x800")
global e1
def callback(event):
if(format(k=event.char(13)))):
msg = e1.get()
print(msg)
Label(root, text="Student Name").place(x=140, y=40)
e1 = Entry(root)
e1.place(x=140, y=10)
e1.bind('<Key>',callback)
root.mainloop()
Try this out
from tkinter import *
root = Tk()
root.geometry("800x800")
def callback(event):
msg = e1.get()
print(msg)
Label(root, text="Student Name").place(x=140, y=40)
e1 = Entry(root)
e1.place(x=140, y=10)
e1.bind('<Return>',callback) #<Return> is equivalent to your Enter key
root.mainloop()
When you click on Enter key, on the entry widget, then the function gets called and the output will be printed out. I also removed the global as it makes no sense to use it in outside functions.
Hope it helped you out.
Cheers
I am creating a GUI that builds information about a person. I want the user to select their birth month using a drop down bar, with the months configured earlier as a list format.
from tkinter import *
birth_month = [
'Jan',
'Feb',
'March',
'April'
] #etc
def click():
entered_text = entry.get()
Data = Tk()
Data.title('Data') #Title
label = Label(Data, text='Birth month select:')
label.grid(row=2, column=0, sticky=W) #Select title
How can I create a drop down list to display the months?
To create a "drop down menu" you can use OptionMenu in tkinter
Example of a basic OptionMenu:
from Tkinter import *
master = Tk()
variable = StringVar(master)
variable.set("one") # default value
w = OptionMenu(master, variable, "one", "two", "three")
w.pack()
mainloop()
More information (including the script above) can be found here.
Creating an OptionMenu of the months from a list would be as simple as:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
mainloop()
In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:
from tkinter import *
OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc
master = Tk()
variable = StringVar(master)
variable.set(OPTIONS[0]) # default value
w = OptionMenu(master, variable, *OPTIONS)
w.pack()
def ok():
print ("value is:" + variable.get())
button = Button(master, text="OK", command=ok)
button.pack()
mainloop()
I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.
Here Is my function which will let you create a Combo Box with values of files stored in a Directory and Prints the Selected Option value in a Button Click.
from tkinter import*
import os, fnmatch
def submitForm():
strFile = optVariable.get()
# Print the selected value from Option (Combo Box)
if (strFile !=''):
print('Selected Value is : ' + strFile)
root = Tk()
root.geometry('500x500')
root.title("Demo Form ")
label_2 = Label(root, text="Choose Files ",width=20,font=("bold", 10))
label_2.place(x=68,y=250)
flist = fnmatch.filter(os.listdir('.'), '*.mp4')
optVariable = StringVar(root)
optVariable.set(" Select ") # default value
optFiles = OptionMenu(root, optVariable,*flist)
optFiles.pack()
optFiles.place(x=240,y=250)
Button(root, text='Submit', command=submitForm, width=20,bg='brown',fg='white').place(x=180,y=380)
root.mainloop()