Trouble importing a module with radiobuttons - python - python

Hi I have made a program that runs various other programs. I import the module and it works fine for programs that don't have radiobuttons involved. The programs with radiobuttons work fine when they are ran by themselves. When they are ran through my menu program, the radiobuttons do not give the IntVar values. Anybody have any ideas on how to fix this? The modules are my ow programs but they all use Tkinter. Here is the code for the menu:
from Tkinter import *
def cmd():
if var.get() == 1:
import animal_age_calculator
animal_age_calculator.createDisplay()
if var.get() == 2:
import temperatureCalculator
temperatureCalculator.createDisplay()
if var.get() == 3:
import calculator
calculator.createDisplay()
if var.get() == 4:
import currencyConverter
currencyConverter.createDisplay()
def createDisplay():
global var
root = Tk()
root.title('Calculator')
title = Label(root, text='Please Select which Calculator you would like to use', font=50)
title.grid(row=0, column=0)
calcType = Frame(root)
calcType.grid(row=1, column=0)
var = IntVar()
animal = Radiobutton(calcType, text='Animal Age Calculator', variable=var, value=1)
animal.pack()
tempConverter = Radiobutton(calcType, text='Temperature Calculator', variable=var, value=2)
tempConverter.pack()
calc = Radiobutton(calcType, text='Calculator', variable=var, value=3)
calc.pack()
currency = Radiobutton(calcType, text='Currency Converter', variable=var, value=4)
currency.pack()
select = Button(root, text='Go', command=cmd)
select.grid(row=2, column=0)
root.mainloop()
if __name__ == '__main__':
createDisplay()
Here is the code for one of the radiobutton programs:
from Tkinter import *
def convert(temperature):
global var4
a = var4.get()
print(str(a))
if a == 1:
print 'test2'
display.delete(1.0, END)
finalTemp = int(temperature)*1.8+32
finalTemp = round(finalTemp, 1)
display.insert(INSERT, finalTemp)
if a == 2:
display.delete(1.0,END)
finalTemp = int(temperature)-32/1.8
finalTemp = round(finalTemp, 1)
display.insert(INSERT, finalTemp)
def createDisplay():
global display, var4
root = Tk()
root.title('Temperature Converter')
root.resizable(width=False, height=False)
title = Label(root, text="Welcome to the temperature converter", font=36)
title.grid(row=0, column=1, columnspan=3)
selTemp = LabelFrame(root, text="Please select your temperature")
selTemp.grid(row=1, column=2)
temp = Scale(selTemp, orient=HORIZONTAL, sliderlength=20, from_=0, to=250, length=250, command=convert)
temp.pack()
temperature = temp.get()
displayFrame = LabelFrame(root, text="Your converted temperature is")
displayFrame.grid(row=1, column=3)
display = Text(displayFrame, width=6, height=1)
display.pack()
var4 = IntVar()
tempType = LabelFrame(root, text='Please select your temperature you would like to convert')
tempType.grid(row=1, column=1)
celcius = Radiobutton(tempType, text="Celcius", variable=var4, value=1)
celcius.pack()
fahrenheit = Radiobutton(tempType, text="Fahrenheit", variable=var4, value=2)
fahrenheit.pack()
root.mainloop()
if __name__ == '__main__':
createDisplay()

The crux of the problem is that you're creating two instances of Tk. You can't do that. Tkinter is designed for you to only ever create a single instance of Tk at any one time. Your modules should create instances of Toplevel rather than instances of Tk, and they should not create a new event loop when the module is imported.

Related

tkinter print values on "enter" press

I need to print values on Screen When "Enter is pressed"
but not able to do so...
Currently its done with onClick method on button click...
How can Implement it?
I have tried
root.bind('<Return>', getvals) but didn't work i get error
return self.func(*args) TypeError: getvals() takes 0 positional
arguments but 1 was given
from tkinter import *
root = Tk()
def getvals():
print("Submitting form")
print(f"{namevalue.get(), phonevalue.get(), gendervalue.get(), emergencyvalue.get(), paymentmodevalue.get(), foodservicevalue.get()} ")
root.geometry("644x344")
#Heading
Label(root, text="Welcome to Harry Travels", font="comicsansms 13 bold", pady=15).grid(row=0, column=3)
#Text for our form
name = Label(root, text="Name")
phone = Label(root, text="Phone")
gender = Label(root, text="Gender")
emergency = Label(root, text="Emergency Contact")
paymentmode = Label(root, text="Payment Mode")
#Pack text for our form
name.grid(row=1, column=2)
phone.grid(row=2, column=2)
gender.grid(row=3, column=2)
emergency.grid(row=4, column=2)
paymentmode.grid(row=5, column=2)
# Tkinter variable for storing entries
namevalue = StringVar()
phonevalue = StringVar()
gendervalue = StringVar()
emergencyvalue = StringVar()
paymentmodevalue = StringVar()
foodservicevalue = IntVar()
#Entries for our form
nameentry = Entry(root, textvariable=namevalue)
phoneentry = Entry(root, textvariable=phonevalue)
genderentry = Entry(root, textvariable=gendervalue)
emergencyentry = Entry(root, textvariable=emergencyvalue)
paymentmodeentry = Entry(root, textvariable=paymentmodevalue)
# Packing the Entries
nameentry.grid(row=1, column=3)
phoneentry.grid(row=2, column=3)
genderentry.grid(row=3, column=3)
emergencyentry.grid(row=4, column=3)
paymentmodeentry.grid(row=5, column=3)
#Checkbox & Packing it
foodservice = Checkbutton(text="Want to prebook your meals?", variable = foodservicevalue)
foodservice.grid(row=6, column=3)
#Button & packing it and assigning it a command
Button(text="Submit to Harry Travels", command=getvals ).grid(row=7, column=3)
#enter press displays the value of the entry
# root.bind('<Return>', getvals)
root.mainloop()
Use:
def getvals(event=None):
and un-comment
root.bind('<Return>', getvals)
That's it ...
P.S. The 'trick' is to allow one parameter in getvals, but preset it with a default value in case there is no parameter passed to the function. This way can getvals be used for both button click and key-press.

How to set the text in tkinter?

I want to set the answer using the set() method without writing it in the text attribute in the Label and also I want to change the message without displaying the messages over each other.
I want the new message to appear and the one before it to disappear. I tried to use the set() and get() methods but it used to return its default value without using the value in the set() method and I don't know why.
from tkinter import *
from tkinter import messagebox
from PIL import ImageTk,Image
root= Tk()
root.title("Project")
root.geometry('500x600')
root.title('Choose Answer')
var = IntVar()
textt = StringVar()
print(textt.set('Clicked..........'))
def Result():
print(textt.set('You Clicked....................'))
if(var.get() == 1):
print(var.get())
print(textt)
textt.set('You Clicked')
resultText = Label(root, text=textt , fg='white',bg='gray', width=40)
resultText.place(x=100,y=200)
else:
textt.set('You did\'t Click')
resultText = Label(root, text=textt, fg='white',bg='grey', width=40)
resultText.place(x=100,y=200)
checkBox = Checkbutton(root, text='Did you Study Math', variable=var, bg='grey')
checkBox.place(x=50,y=50)
button = Button(root, text='Select', fg='white', bg='grey',font='sans-serif',command=Result)
button.place(x=50,y=100)
root.mainloop()
This should work:
from tkinter import *
root = Tk()
root.title("Project")
root.geometry('500x600')
root.title('Choose Answer')
var = IntVar()
textt = StringVar()
resultText = Label(root, textvariable=textt , fg='white',bg='gray', width=40)
resultText.place(x=100,y=200)
def Result():
print(var.get())
if var.get() == 1:
textt.set('You Clicked')
else:
textt.set('You didn\'t Click')
checkBox = Checkbutton(root, text='Did you Study Math', variable=var, bg='grey')
checkBox.place(x=50,y=50)
button = Button(root, text='Select', fg='white', bg='grey',font='sans-serif',command=Result)
button.place(x=50,y=100)
root.mainloop()
When you create resultText, instead of setting the text argument to textt, you need to set the textvariable argument to text. That way, the text of the variable is automatically changed when you change textt.
I removed all the lines where resultText was recreated and re-placed, and just created it once before defining Result(). Also, I removed from tkinter import messagebox, because you already import it when you call from tkinter import *. Just a note: wildcard imports are discouraged, so try to avoid using them in the future.

Python - Tkinter - Label Not Updating

Any ideas why the leftresult_label label does not update? The function seems to work but the label does not update. I have looked everywhere and can't find an answer. The 'left' value gets set but the label does not change.
from tkinter import *
root = Tk(className="Page Calculator")
read = IntVar()
total = IntVar()
left = IntVar()
read.set(1)
total.set(1)
left.set(1)
read_label = Label(root,text="Pages Read:")
read_label.grid(column=1, row=1)
total_label = Label(root,text="Total Pages:")
total_label.grid(column=1, row=2)
read_entry = Entry(root,textvariable=read)
read_entry.grid(column=2, row=1)
total_entry = Entry(root,textvariable=total)
total_entry.grid(column=2, row=2)
def func1():
left.set(total.get() - read.get())
print(left.get())
calculate_button = Button(root,text="Calculate",command= func1)
calculate_button.grid(column=2, row=3)
percenet_label = Label(root,text="Percent Finished:")
percenet_label.grid(column=1, row=4)
left_label = Label(root,text="Pages Left:")
left_label.grid(column=1, row=5)
percenetresult_label = Label(root,text=left.get())
percenetresult_label.grid(column=2, row=4)
leftresult_label = Label(root,text="")
leftresult_label.grid(column=2, row=5)
root.mainloop()
To make the function do the job, you'd rather have your label:
leftresult_label = Label(root, textvariable=left)
Once it's tkinter class variable, tkinter takes care about when you change the value. Once you click the button,
def func1():
left.set(total.get() - read.get())
percent.set(int(read.get()*100/total.get()))
left and percent values, which are instances of tkinter.IntVar() class have immidiate effect on widgets (labels in this case) where those values are set as textvariable, just as you have it at Entry widgets.
Here is full code:
from tkinter import *
root = Tk(className="Page Calculator")
read = IntVar()
total = IntVar()
left = IntVar()
percent = IntVar()
read.set(1)
total.set(1)
left.set(1)
percent.set(1)
def func1():
left.set(total.get() - read.get())
percent.set(int(read.get()*100/total.get()))
read_label = Label(root,text="Pages Read:")
read_label.grid(column=1, row=1)
read_entry = Entry(root,textvariable=read)
read_entry.grid(column=2, row=1)
total_label = Label(root,text="Total Pages:")
total_label.grid(column=1, row=2)
total_entry = Entry(root,textvariable=total)
total_entry.grid(column=2, row=2)
calculate_button = Button(root,text="Calculate",command= func1)
calculate_button.grid(column=2, row=3)
percenet_label = Label(root,text="Percent Finished:")
percenet_label.grid(column=1, row=4)
left_label = Label(root,text="Pages Left:")
left_label.grid(column=1, row=5)
percenetresult_label = Label(root,textvariable=percent)
percenetresult_label.grid(column=2, row=4)
leftresult_label = Label(root,textvariable=left)
leftresult_label.grid(column=2, row=5)
root.mainloop()
code including progress bar. update_idletasks() used to keep label and progress bar running.
from tkinter import *
from tkinter import ttk
root = Tk()
root.title('Counter Test')
root.iconbitmap('IT.ico')
root.geometry("800x400")
def missing():
while i < 100:
progress1['value'] = i
label1.config(text=progress1['value'])
root.update_idletasks()
i += 1
progress1 = ttk.Progressbar(root, orient=HORIZONTAL, length=250, mode='determinate')
progress1.pack(pady=15)
label1 = Label(root, text="")
label1.pack(pady=15)
button_1 = Button(root, text="Missing", command=missing)
button_1.pack(pady=15)
button_q = Button(root, text="Quit", command=root.destroy)
button_q.pack(pady=15)
root.mainloop()
so to update controls immediately, like updating labels and TreeView elements this code worked for me.
window = tk.Tk()
window.update_idletasks()

Tkinter python: issue with clearing out the widget

Someone please help me figure this out.
I have the following problem in Tkinter Python. The problem is that the text is overlaying with the previous text. and/or is copying below that.
I've tried to use label.config(root).pack() instead of Label(root, text="").pack()
This kinda solves the problem it starts to write over the previous text but there are 2 problems with this.
1: the text old text/Entrys all still there, it just overlays.
2: this only works with label.config, and I would also like this to work with buttons and Entrys(textbox)
I've also tried .pack_forget() and .destroy() but unfortunately it did nothing.
CODE
from tkinter import *
import pickle
import time
import os
def new_profile():
global Var1, Var2
var1 = StringVar()
var2 = StringVar()
Label(root, text="Create a new profile").pack()
Label(root, text="User Name").pack()
Entry(root, textvariable=var1).pack()
Label(root, text="Password").pack()
Entry(root, textvariable=var2).pack()
Button(root, text="Create", command=create_profile).pack()
Var1, Var2 = var1, var2
return
def create_profile():
text1 = Var1.get()
text2 = Var2.get()
print(text1)
dict = {}
dict['Name'] = text1
dict['Password'] = text2
pickle.dump(dict, open("test.txt", "wb"))
dict1 = pickle.load(open("test.txt", "rb"))
if dict1['Name'] == text1 and dict1['Password'] == text2:
Label(root, text="").pack()
Label(root, text="Profile creation successful", ).pack()
Label(root, text="Name:" + " " + text1).pack()
Label(root, text="Password:" + " " + text2).pack()
else:
Label(root, text="Something went wrong while creating your profile.", ).pack()
return
def load_profile():
select = "Load profile.."
label.config(text=select)
return
root = Tk()
root.geometry("500x400+300+300")
root.title("client")
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New Profile", command=new_profile)
filemenu.add_command(label="Load Profile", command=load_profile)
menubar.add_cascade(label="Profile Options", menu=filemenu)
root.config(menu=menubar)
label = Label(root)
label.pack()
root.mainloop()
create a array such as
on_screen = []
at the start then name your widgets and and add them to the array
password_label = Label(root, text="Password").pack()
password = Entry(root, textvariable=var2).pack()
on_screen.append(password)
on_screen.append(password_label)
then use a for loop to destroy all the widgets in the array
for w in on_screen:
w.destroy()

is it possible to put forms in a notebook widget using tkinter and python?

I have been trying to desing a form in tkinter using python, but unfortunately I am stuck again, but now putting a form into the notebook I already have. I have run them separately and they work perfect, the problem starts when I try to put them together.
For example, if I write in "componentComb= ttk.Combobox(frameOne, width="19")" instead of frameOne I put firstStep which is what I want to do (merge them), I have an error like this:
componentComb= ttk.Combobox(firstStep, width="19")
NameError: name 'firstStep' is not defined
Which I don't understand, I have already defined, but probably wrong!!! Can you help me with this problem?
Below you have the code I have been "fighting" with, and I hope you can help me!
Thanks in advance
Here is my code:
#Starts
import Tkinter
from Tkinter import *
from ttk import *
import tkMessageBox
import ttk
# start of GUI code
root = Tk()
root.title("Model A")
root.minsize(1000, 150)
root.maxsize(1100, 200)
notebook = ttk.Notebook(root)
notebook.pack(fill='both', expand='yes')
notebook.pressed_index = None
# Child Frame
frameOne = Tkinter.Frame(notebook, bg='white')
frameOne.pack(fill='both', expand=True)
frameTwo = Tkinter.Frame(notebook, bg='white')
frameTwo.pack(fill='both', expand=True)
frameThree= Tkinter.Frame(notebook, bg='white')
frameThree.pack(fill='both', expand=True)
frameFour= Tkinter.Frame(notebook, bg='white')
frameFour.pack(fill='both', expand=True)
# Pages
notebook.add(frameOne, text='Standard')
notebook.add(frameTwo, text='TID')
notebook.add(frameThree, text='MEE')
notebook.add(frameFour, text='Final')
# Merging form and notebook
def defocus(event):
event.widget.master.focus_set()
if __name__ == '__main__':
firstStep = Tkinter.Label(notebook, text=" 1. Enter Main Details: ", font=("fixedsys", "16","bold italic"))
firstStep.grid(row=2, columnspan=7, sticky='W', \
padx=5, pady=5, ipadx=5, ipady=5)
#Main Selection
componentComb= ttk.Combobox(frameOne, width="19")
componentComb = Combobox(frameOne, state="readonly", values=("TGB", "RST", "CCPa"))
componentComb.grid(column=4, row=0, columnspan="5", sticky="nswe")
componentComb.set("Main Selection")
#Temperature Selection
tempComb = ttk.Combobox(frameOne, width="14")
tempComb = Combobox(frameOne, state="readonly", values=("-40", "-30", "-20","-10", "0", "10","20", "30"))
tempComb.grid(column=0, row=2, columnspan="2", sticky="w")
tempComb.set("Temperature Selection")
#Device Type Selection
DeviceTypeComb = ttk.Combobox(frameOne, width="14")
DeviceTypeComb = Combobox(frameOne, state="readonly", values=("QML", "Non-QML"))
DeviceTypeComb.grid(column=3, row=2, columnspan="2", sticky="w")
DeviceTypeComb.set("Device Type Selection")
#Junction Temperature Selection
JunctionTempComb = ttk.Combobox(frameOne, width="16")
JunctionTempComb = Combobox(frameOne, state="readonly", values=("-40", "-30", "-20","-10", "0", "10","20", "30"))
JunctionTempComb.grid(column=5, row=2, columnspan="2", sticky="w")
JunctionTempComb.set("Junction Temp Selection")
#Chip Area in Cm2 Selection
ChipAreaComb = ttk.Combobox(frameOne, width="12")
ChipAreaComb = Combobox(frameOne, state="readonly", values=("0.001","0.002","0.003","0.004","0.005","0.006"))
ChipAreaComb.grid(column=7, row=2, columnspan="2", sticky="e")
ChipAreaComb.set("Chip Area Selection")
#Time of Exposure
TimeOfExpoComb = ttk.Combobox(frameOne, width="12")
TimeOfExpoComb = Combobox(frameOne, state="readonly", values=("1", "2", "3","4", "5"))
TimeOfExpoComb.grid(column=9, row=2, columnspan="2", sticky="w")
TimeOfExpoComb.set("Time of Exposure")
root.mainloop()
firstStep is a local variable in the defocus function, and you are trying to access it in a global scope.
You have to define it outside of the function so that it has a meaning in the global scope. But note that because you are assigning it within the function, you need to use the global keyword so that it doesn't think you're introducing a new local variable with the same name.
This should work:
firstStep = None #define the variable globally
def defocus(event):
event.widget.master.focus_set()
if __name__ == '__main__':
global firstStep # we want to reassign the global version of this variable
firstStep = Tkinter.Label(notebook, text=" 1. Enter Main Details: ", font=("fixedsys", "16","bold italic"))
firstStep.grid(row=2, columnspan=7, sticky='W', \
padx=5, pady=5, ipadx=5, ipady=5)
componentComb= ttk.Combobox(firstStep, width="19")

Categories

Resources