I couldnt seem to find a way to make my program realise that ive selected a button, so i changed the function of the celcius to farenheit to try to make it change a boolean value to determine what conversion the program is doing
def celcius_to_farenheit(_event = None):
c_to_f = True
f_to_c = False
the idea being later i can use if statments later in the end result function to find what conversion its doing and display results in the status bar
def end_result():
if c_to_f == True:
converted_temperature = (valid_temperature * 9/5) + 32
label_status.configure(text = converted_temperature, fg = "Orange")
currently i seem to have functions running without me pressing buttons as well, when start the program it immediatly goes to the error message ive created for input muct be numeric even if i havent pressed the celcius to farenheit button.
Any help regarding how to propely have my celcius to farenheit and farenheit to celcius buttons confirm its a float and change a value to use for determining which calculation its using would be helpfull. Knowing why the error message comes up automatically is a bonus.
Below is my code thank you for your time and help.
import sys
from tkinter import *
from tkinter.tix import *
c_to_f = True
def clear_reset(_event = None):
entry_temperature.delete(0, END)
label_status.configure(text = "All data cleared", fg = "Orange")
def end_program(_event = None):
sys.exit()
def convert_temp(_event = None):
try:
valid_temperature = float(entry_temperature.get())
except:
label_status.configure(text = "Input must be numeric", fg = "Orange")
def end_result():
if c_to_f == True:
converted_temperature = (valid_temperature * 9/5) + 32
label_status.configure(text = converted_temperature, fg = "Orange")
def celcius_to_farenheit(_event = None):
c_to_f = True
f_to_c = False
def farenheit_to_celcius(_event = None):
f_to_c = True
c_to_f = False
window = Tk()
window.geometry("550x200")
window.resizable(False, False)
window.title("Temperature Conversion")
tooltip = Balloon(window)
label_input_Temperature = Label(text = "Temperature",fg = "Green")
label_input_Temperature.grid(row= 0, column=0)
entry_temperature = Entry(window, bg = "light blue" )
entry_temperature.grid(row=0, column=1)
temp_button_c_to_f = Button(window, text = "Celcius to Farenheit", command = celcius_to_farenheit)
temp_button_c_to_f.grid(row = 1, column=0)
window.bind('<Shift-c>', celcius_to_farenheit)
tooltip.bind_widget(temp_button_c_to_f, msg = "Shift + C")
temp_button_f_to_c = Button(window, text = "Farenheit to Celcius")
temp_button_f_to_c.grid(row = 1, column = 1 )
conversion_button = Button(window, text = "Convert", command = convert_temp)
conversion_button.grid(row = 2, column = 0,padx =0 )
window.bind('<Enter>', convert_temp)
tooltip.bind_widget(conversion_button, msg = "Enter")
clear_button = Button(window, text = "Clear", command = clear_reset)
clear_button.grid(row = 2, column = 1)
window.bind('<Control-c>', clear_reset)
tooltip.bind_widget(clear_button, msg = "Ctrl + C")
exit_button = Button(window, text = "Exit")
exit_button.grid(row = 2, column = 2, padx = 20, pady = 20)
window.bind('<Control-x>', end_program)
tooltip.bind_widget(exit_button, msg = "Ctrl + X")
label_status = Label(window, width = 50, borderwidth = 2, relief= RIDGE,bg= "Grey" )
label_status.grid(row = 4, column = 1)
tooltip.bind_widget(label_status, msg = "Displays results / error messages")
label_status.configure(text = "Enter in your temperature and select your conversion", fg = "Orange")
window.mainloop()
I would like to make a money counter with a input box that changes the speed of the counter to display the inputed amount of money per hour, however it's very choppy and doesn't seem to work with different numbers. any advice?
import tkinter as tk
root = tk.Tk()
money = 0
money_per_hour = 1000
root.minsize(500,300)
def monies():
global money_per_hour
box = spinbox.get()
box = int(box)
final = 3600/box
final = round(final)
final = final * 1000
money_per_hour = final
countup()
button = tk.Button(text = "show me the money", fg = "green", command = monies)
button.pack(side = "bottom")
spinbox = tk.Spinbox(from_=0, to=1000000, width=5)
spinbox.pack(side = "bottom")
label = tk.Label(root, text = "$" + str(money), foreground = "green", font = ('calibri', 40, 'bold'))
label.pack()
def countup():
global money
money += 1
label['text'] = "$" + str(money)
root.after(money_per_hour, countup)
root.after(money_per_hour, countup)
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 4 years ago.
I am trying to create a counter for Jeopardy so that my Mom and I can keep score. Currently the program that I am creating is assigning the values to variables and then not performing the command when I press the button in the window. I am running Python 2.7.13.`
import Tkinter as tk
root = tk.Tk()
root.title("Jeopardy Scores")
def ChangeScore(User,Value):
if User == 1:
Score = int(JScore.get())
JScore.set(Score + Value)
#J = JScore.get()
#print J
#SayHi()
else:
Score = int(MScore.get())
MScore.set(Score + Value)
#M = MScore.get()
#print M
#SayHi()
#def SayHi(*args):
#print 'hi'
MainFrame = tk.Frame(root)
MainFrame.grid(column=0, row=0)
MainFrame.columnconfigure(0, weight=1)
MainFrame.rowconfigure(0, weight=1)
JScore = tk.StringVar()
MScore = tk.StringVar()
JScore.set(0)
MScore.set(0)
JL = tk.Label(MainFrame, text = "Joey's Score", padx = 10, pady = 2)
JL.config(bg = 'blue', fg = 'yellow', font = ('Arial',30, 'bold'))
JL.grid(column = 0, row = 0)
ML = tk.Label(MainFrame, text = "Mom's Score", padx = 10, pady = 2)
ML.config(bg = 'blue', fg = 'yellow', font = ('Arial',30, 'bold'))
ML.grid(column = 1, row = 0)
JSS = tk.Label(MainFrame, textvariable=JScore ,padx = 122)
JSS.config(bg = 'blue', fg = 'yellow', font = ('Arial',30, 'bold'))
JSS.grid(column = 0, row = 1)
MSS = tk.Label(MainFrame, textvariable = MScore,padx = 122)
MSS.config(bg = 'blue', fg = 'yellow', font = ('Arial',30, 'bold'))
MSS.grid(column = 1, row = 1)
for i in range(1,6):
Score = tk.IntVar()
Score.set(i*200)
Score1 = 200*i
JButton = tk.Button(MainFrame, textvariable = Score, command =
ChangeScore(1,Score1))
JButton.grid(column = 0, row = 1+i)
MButton = tk.Button(MainFrame, textvariable = Score, command =
ChangeScore(2,Score1))
MButton.grid(column = 1, row = 1+i)
JButton = tk.Button(MainFrame, text = '400', command = ChangeScore(1,400))
JButton.grid(column = 0, row = 7)
root.mainloop()
The code runs and produces this Window
Note that no buttons have been pressed when the picture was taken. It appears that all the buttons are 'being pressed' when the code runs and then nothing happens when i press the buttons afterwards.
I have no experience with Tkinter beyond the small information that has allowed me to do this and I have a bit more experience with Python. I am mainly doing this as an excerise for myself to improve my coding and to acutally use for Jeopardy!. Any help would be appreciate
Here the command parameter for Button should be a callable. You should not call the function yourself and pass the return value to it. Instead, you provide a function that is to be called later.
So change you code to things like
command=lambda: ChangeScore(1, 400)
to create a lambda to be called later will solve the problem.
I have a long chunk of code. I do not want to paste it all here, so let me explain what I am trying to accomplish here. Based on a number provided by the user I want to create that many text boxes and then get what is entered into that text box and insert that into the dictionary. I have tried this a few ways and just cannot get it to work correctly. The list is either empty or it only contains the last text box as the value for each key.
def multiple_choice():
def add():
top.destroy()
top = Tk()
top.title("Add Question")
w = 800
h = 800
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
top.geometry('%dx%d+%d+%d' % (w, h, x, y))
question = Label(top, text="Question to be asked?", font = "Times 14 bold", fg = "blue")
question.grid(row = 2, column = 4)
questionText = Text(top, borderwidth = 5, width=50,height=5, wrap=WORD, background = 'grey')
questionText.grid(row = 3, column = 4)
numQuestions = Label(top, text = "Number of answer choices?", font = "Times 14 bold", fg = "blue")
numQuestions.grid(row = 4, column=4)
num = Entry(top, bd = 5)
num.grid(row=5, column = 4)
answerList = {}
def multiple():
def preview():
preview = Tk()
top.title("Question Preview")
w = 500
h = 500
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
top.geometry('%dx%d+%d+%d' % (w, h, x, y))
title = Label(preview, text = "Short Answer Question Preview", font = "Times 18 bold", fg = "blue" )
title.grid(row = 0, column = 2)
qtext = "Question text will read: "
ques = Label(preview, text = qtext)
ques.grid(row=1, column = 2)
ques2 = Label( preview, text = questionText.get("1.0",END))
let = 'A'
i = 1
for word in answerList:
prev = let + ": " + word
ans = Label(preview, text = prev)
ans.grid(row=1+i, column = 2)
let = chr(ord(let) + 1)
answerCor = "The correct answer(s): "
a = Label(preview, text = answerCor)
a.grid(row=4, column = 2)
b = Label(preview, text = cor.get)
b.grid(row=5, column = 2)
if num.get().isdigit():
number = int(num.get())
AnswerChoices = Label(top, text = "Answer Choices?", font = "Times 14 bold", fg = "blue")
AnswerChoices.grid(row = 6, column=4)
i = 0
let = 'A'
while i < number:
letter = Label(top, text = let)
letter.grid(row = 8+(i*4), column = 3)
answer = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
answer.grid(row = 8+(i*4), column = 4)
answerList[let] = answer.get("1.0",END)
i = i+1
let = chr(ord(let) + 1)
print answerList
correct = Label(top, text = "Correct Answer(s) (seperated by commas)",
font = "Times 14 bold", fg = "blue")
correct.grid(row =99 , column=4)
cor = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
cor.grid(row=100, column = 4)
else:
error = Tk()
w = 500
h = 100
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
error.geometry('%dx%d+%d+%d' % (w, h, x, y))
text = "ERROR: You must enter an integer number"
Label(error,text = text, fg = "red", font = "Times 16 bold").pack()
MyButton5 = Button(top, text="Preview Question", width=20, command = preview, anchor=S)
MyButton5.grid(row=102, column=5)
MyButton4 = Button(top, text="Finish and Add Question", width=20, command = add, anchor=S)
MyButton4.grid(row=102, column=2)
but = Button(top, text="Submit", width=10, command = multiple)
but.grid(row=6, column = 4)
top.mainloop()
def button():
MyButton21 = Button(quiz, text="Short Answer Question", width=20, command = short_answer)
MyButton21.grid(row=8, column=2)
MyButton22 = Button(quiz, text="True/False Question", width=20, command = true_false)
MyButton22.grid(row=8, column=4)
MyButton23 = Button(quiz, text="Multiple Choice Question", width=20, command = multiple_choice)
MyButton23.grid(row=9, column=2)
#MyButton24 = Button(quiz, text="Matching Question", width=20, command = matching)
#MyButton24.grid(row=9, column=4)
MyButton25 = Button(quiz, text="Ordering Question", width=20, command =order)
MyButton25.grid(row=10, column=2)
MyButton26 = Button(quiz, text="Fill in the Blank Question", width=20, command = fill_blank)
MyButton26.grid(row=10, column=4)
MyButton3 = Button(quiz, text="Finsh Quiz", width=10, command = quiz)
MyButton3.grid(row=12, column=3)
quiz = Tk()
w = 700
h = 300
ws = quiz.winfo_screenwidth()
hs = quiz.winfo_screenheight()
x = 0
y = 0
quiz.geometry('%dx%d+%d+%d' % (w, h, x, y))
quiz.title("eCampus Quiz Developer")
L1 = Label(quiz, text="Quiz Title?")
L1.grid(row=0, column=0)
E1 = Entry(quiz, bd = 5)
E1.grid(row=0, column=3)
name_file = E1.get()
name_file = name_file.replace(" ", "")
name_file = name_file + ".txt"
with open(name_file,"w") as data:
MyButton1 = Button(quiz, text="Submit", width=10, command = button)
MyButton1.grid(row=1, column=3)
quiz.mainloop()
I am trying to create the dictionary using this chunk of code:
i = 0
let = 'A'
while i < number:
letter = Label(top, text = let)
letter.grid(row = 8+(i*4), column = 3)
answer = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
answer.grid(row = 8+(i*4), column = 4)
answerList[let] = answer.get("1.0",END)
i = i+1
let = chr(ord(let) + 1)
I have even tried putting a loop in the preview function but that is when the last box was the only value contained in the dictionary. Any ideas would be appreciated
Please see my commeneted snippet below which demonstrates this:
from tkinter import *
class App:
def __init__(self, root):
self.root = root
self.entry = Entry(self.root) #entry to input number of entries later
self.button = Button(self.root, text="ok", command=self.command) #calls command to draw the entry boxes
self.frame = Frame(self.root)
self.entry.pack()
self.button.pack()
self.frame.pack()
def command(self):
self.frame.destroy() #destroys frame and contents
self.frame = Frame(self.root) #recreates frame
self.text = [] #empty array to store entry boxes
for i in range(int(self.entry.get())):
self.text.append(Entry(self.frame, text="Question "+str(i))) #creates entry boxes
self.text[i].pack()
self.done = Button(self.frame, text="Done", command=self.dict) #button to call dictionary entry and print
self.done.pack()
self.frame.pack()
def dict(self):
self.dict = {}
for i in range(len(self.text)):
self.dict.update({self.text[i].cget("text"): self.text[i].get()})
#the above line adds a new dict entry with the text value of the respective entry as the key and the value of the entry as the value
print(self.dict) #prints the dict
root = Tk()
App(root)
root.mainloop()
The above asks the user how many entry widgets they want to create, fills a frame with those entry widgets and then iterates through the list which contains them on the press of a button, adding a new dictionary entry for each entry widget, where the key of the dict is the attribute text for each entry and the value of the dict is the value of each entry.
Using the Tkinter module, I am try to elicit an action based on the certain selection of an option menu and cancel that action if the option menu is not on the designated selection. The problem is that the program will compile except when both option menus = "treble clef" it somewhat stops working. I have tried using an if statement which works fine except I'm not sure how to get rid of the label it calls.
originalKey = Label(window, text = "Original Key Signature", bg = 'black', fg = 'white')
originalKey.pack()
oKey = StringVar(window)
oKey.set("Select") # initial value
optionold = OptionMenu(window, oKey, "treble clef", "bass clef", "alto clef")
optionold.config(bg = 'black', fg = 'white')
optionold.pack()
#new key selections option menu
def displayKey(str):
while nKey.get() == "treble clef" and oKey.get() == "treble clef":
testpic = Label(window, image = logoimage, bg = 'black')
testpic.pack()
break
newKey = Label(window, text = "New Key Signature", bg = 'black', fg = 'white')
newKey.pack()
nKey = StringVar(window)
nKey.set("select") # initial value
optionnew = OptionMenu(window, nKey, "treble clef", "bass clef", "alto clef",
command = displayKey)
optionnew.config(bg = 'black', fg = 'white')
optionnew.pack()