Why is my Tkinter button not executing my function? - python

from tkinter import *
import random
from collections import Counter
root = Tk()
root.title("Random")
root.geometry("600x400")
root.resizable(False, False)
def open_saw():
saw_wn = Tk()
saw_wn.title("Random App - Spin a Wheel")
saw_wn.geometry("600x400")
saw_wn.resizable(False, False)
saw_wn.mainloop()
def open_coin():
c_wn = Tk()
c_wn.title("Random App - Flip a Coin")
c_wn.geometry("600x400")
c_wn.resizable(False, False)
Label(c_wn, text=" ").grid(row=0,
column=0)
Label(c_wn, text="Flip the coin below!", font=("Yu Gothic UI", 12)).grid(row=0, column=1)
Label(c_wn, text=' ').grid(row=1, column=1)
coin_values = ["Heads", "Tails"]
coin_face = random.choice(coin_values)
def flip():
if coin_face == "Heads":
Label(c_wn, text="Coin: Heads").place(anchor='s')
else:
Label(c_wn, text="Coin: Tails").place(anchor='s')
coin = Button(c_wn, text='coin', padx=100, pady=90, command=flip)
coin.place(relx=0.5, rely=0.5, anchor=CENTER)
c_wn.mainloop()
def open_average():
avg_wn = Tk()
avg_wn.title("Random App - Averages")
avg_wn.geometry("840x300")
Label(avg_wn, text=" ").grid(row=0, column=0)
avg_instruct = Label(avg_wn, text="Enter your values below to get the averages in mean, median, and mode(put a "
"space between commas")
avg_instruct.config(font=("Yu Gothic UI", 10))
avg_instruct.grid(row=0, column=1)
Label(avg_wn, text=" ").grid(row=1, column=0)
entry = Entry(avg_wn)
entry.grid(row=2, column=1)
def calculate():
list_data = entry.get().split(', ')
list_data = [float(i) for i in list_data]
mean = sum(list_data) / len(list_data)
Label(avg_wn, text='Mean').grid(row=5, column=0)
Label(avg_wn, text=str(mean)).grid(row=6, column=0)
list_data_len = len(list_data)
list_data.sort()
if list_data_len % 2 == 0:
median1 = list_data[list_data_len // 2]
median2 = list_data[list_data_len // 2 - 1]
median = (median1 + median2) / 2
else:
median = list_data[list_data_len // 2]
Label(avg_wn, text='Median: ' + str(median)).grid(row=5, column=1)
Label(avg_wn, text=median).grid(row=6, column=1)
list_data_for_mode = Counter(list_data)
get_mode = dict(list_data_for_mode)
mode = [k for k, v in get_mode.items() if v == max(list(list_data_for_mode.values()))]
if len(mode) == list_data_len:
get_mode = ["No mode found"]
else:
get_mode = [str(i) for i in mode]
Label(avg_wn, text="Mode: ").grid(row=5, column=2)
Label(avg_wn, text=get_mode[0]).grid(row=6, column=2)
Label(avg_wn, text=" ").grid(row=3, column=0)
Button(avg_wn, text='Enter', command=calculate).grid(row=4, column=1)
Label(root, text=" ").grid(row=0, column=0)
title = Label(root, text="Welcome to Random")
title.config(font=("Yu Gothic UI", 24))
title.grid(row=0, column=1)
button1 = Button(root, text=" Spin a wheel ", padx=80, pady=25, command=open_saw)
button1.place(x=2.25, y=100)
button2 = Button(root, text="Calculate mean, mode, median, and range", padx=20, pady=25, command=open_average)
button2.place(x=325, y=100)
button3 = Button(root, text="Flip a Coin", padx=125, pady=25, command=open_coin)
button3.place(x=2.25, y=200)
button4 = Button(root, text="Generate a number", padx=82, pady=25)
button4.place(x=325, y=200)
root.mainloop()
I want the function to display heads or tails(randomly). Instead, the function displays nothing and ignores the function. I have also tried printing the value instead of displaying it on tkinter, but it only shows heads and not tails. If any additional details are needed to solve my issue please comment and I will provide additional details.

In the function open_coin, when the button coin is clicked, you are creating the label but not specifying the x and y coordinates in place , and that too creating everytime the button is pressed. So, create a label to display the result and keep changing its text using config.
And the random function is called only once, so keep it inside the flip function to call everytime in order to get a new random coin value.
.
.
CoinLabel = Label(c_wn, text="") #will be used to display the result
CoinLabel.place(relx=0.5, rely=0.2, anchor='s')
def flip():
coin_values = ["Heads", "Tails"]
coin_face = random.choice(coin_values)
print(coin_face)
if coin_face == "Heads":
CoinLabel.config(text="Coin: Heads")
else:
CoinLabel.config(text="Coin: Tails")
coin = Button(c_wn, text='coin', padx=100, pady=90, command=flip)
coin.place(relx=0.5, rely=0.5, anchor=CENTER)
.
.

Related

How to get previous Tkinter value to delete when user clicks a button and generate a new value?

from tkinter import *
import random as r
from collections import Counter
root = Tk()
root.title("Simple Mafs")
root.geometry("600x400")
root.resizable(False, False)
def open_gn():
gn_wn = Tk()
gn_wn.title("Simple Mafs - Generate a number")
gn_wn.geometry("600x400")
gn_wn.resizable(False, False)
Label(gn_wn, text=' ').grid(row=0, column=0)
inst_gn = Label(gn_wn, text='Enter a minimum and maximum value(below 100)')
inst_gn.config(font=("Yu Gothic UI", 12))
inst_gn.grid(row=0, column=1)
Label(gn_wn, text=" Enter a minimum value: ").place(x=295, y=100)
entry_min = Entry(gn_wn)
entry_min.insert(0, "0")
entry_min.place(x=450, y=100)
Label(gn_wn, text=" Enter a maximum value: ").place(x=295, y=200)
entry_max = Entry(gn_wn)
entry_max.insert(0, "99")
entry_max.place(x=450, y=200)
Label(gn_wn, text="Random value is: ").place(x=40, y=40)
def generate_number():
min_ = int(entry_min.get())
max_ = int(entry_max.get())
random_num = r.randint(min_, max_)
d_rn = Label(gn_wn, text=random_num)
d_rn.config(text=random_num, font=("Yu Gothic UI", 30))
d_rn.place(x=40, y=100)
Button(gn_wn, text="Generate", padx=220, pady=25, command=generate_number).place(x=25, y=280)
gn_wn.mainloop()
def open_coin():
c_wn = Tk()
c_wn.title("Simple Mafs - Flip a Coin")
c_wn.geometry("600x400")
c_wn.resizable(False, False)
Label(c_wn, text=" ").grid(row=0,
column=0)
Label(c_wn, text="Flip the coin below!", font=("Yu Gothic UI", 12)).grid(row=0, column=1)
Label(c_wn, text=' ').grid(row=1, column=1)
coin_label = Label(c_wn, text="")
coin_label.place(relx=0.5, rely=0.2, anchor='s')
def flip():
coin_values = ["Heads", "Tails"]
coin_face = r.choice(coin_values)
if coin_face == "Heads":
coin_label.config(text="Coin: Heads")
else:
coin_label.config(text="Coin: Tails")
coin = Button(c_wn, text='coin', padx=100, pady=90, command=flip)
coin.place(relx=0.5, rely=0.5, anchor=CENTER)
c_wn.mainloop()
def open_average():
avg_wn = Tk()
avg_wn.title("Simple Mafs - Averages")
avg_wn.geometry("840x300")
Label(avg_wn, text=" ").grid(row=0, column=0)
avg_instruct = Label(avg_wn, text="Enter your values below to get the averages in mean, median, and mode(put a "
"space between commas")
avg_instruct.config(font=("Yu Gothic UI", 10))
avg_instruct.grid(row=0, column=1)
Label(avg_wn, text=" ").grid(row=1, column=0)
entry = Entry(avg_wn)
entry.grid(row=2, column=1)
def calculate():
list_data = entry.get().split(', ')
list_data = [float(i) for i in list_data]
mean = sum(list_data) / len(list_data)
Label(avg_wn, text='Mean').grid(row=5, column=0)
Label(avg_wn, text=str(mean)).grid(row=6, column=0)
list_data_len = len(list_data)
list_data.sort()
if list_data_len % 2 == 0:
median1 = list_data[list_data_len // 2]
median2 = list_data[list_data_len // 2 - 1]
median = (median1 + median2) / 2
else:
median = list_data[list_data_len // 2]
Label(avg_wn, text='Median: ').grid(row=5, column=1)
Label(avg_wn, text=median).grid(row=6, column=1)
list_data_for_mode = Counter(list_data)
get_mode = dict(list_data_for_mode)
mode = [k for k, v in get_mode.items() if v == max(list(list_data_for_mode.values()))]
if len(mode) == list_data_len:
get_mode = ["No mode found"]
else:
get_mode = [str(i) for i in mode]
Label(avg_wn, text="Mode: ").grid(row=5, column=2)
Label(avg_wn, text=get_mode[0]).grid(row=6, column=2)
Label(avg_wn, text=" ").grid(row=3, column=0)
Button(avg_wn, text='Enter', command=calculate).grid(row=4, column=1)
def rand_stat():
pass
Label(root, text=" ").grid(row=0, column=0)
title = Label(root, text="Welcome to Simple Mafs")
title.config(font=("Yu Gothic UI", 24))
title.grid(row=0, column=1)
button1 = Button(root, text="Generate a random number", padx=80, pady=25, command=open_gn)
button1.place(x=2.25, y=100)
button2 = Button(root, text="Calculate mean, mode, median, and range", padx=20, pady=25, command=open_average)
button2.place(x=325, y=100)
button3 = Button(root, text="Flip a Coin", padx=125, pady=25, command=open_coin)
button3.place(x=2.25, y=200)
button4 = Button(root, text="Calculator", padx=105, pady=25, command=rand_stat)
button4.place(x=325, y=200)
root.mainloop()
Skip to the open_gn() one because that's where the problem is. I want to make an app that can do statistics/random related stuff and in it, I want to create an app that can generate a random number. The app generates the number but the previous value stays and interferes with the current number being generated.
You create new label whenever generate_number() is executed and put that new label on the same position which will overlay previous label.
You need to create the label once outside the function and just update its text inside the function:
def open_gn():
...
Label(gn_wn, text="Random value is: ").place(x=40, y=40)
# create label for generated random number
d_rn = Label(gn_wn, font=("Yu Gothic UI", 30))
d_rn.place(x=40, y=100)
def generate_number():
min_ = int(entry_min.get())
max_ = int(entry_max.get())
random_num = r.randint(min_, max_)
d_rn.config(text=random_num) # update label
...

My program is returning an error message saying that the module random doesn't have an attribute called randint

from tkinter import *
import random
from collections import Counter
root = Tk()
root.title("Random")
root.geometry("600x400")
root.resizable(False, False)
def open_gn():
gn_wn = Tk()
gn_wn.title("Random App - Generate a number")
gn_wn.geometry("600x400")
gn_wn.resizable(False, False)
Label(gn_wn, text=' ').grid(row=0, column=0)
inst_gn = Label(gn_wn, text='Enter a minimum and maximum value')
inst_gn.config(font=("Yu Gothic UI", 12))
inst_gn.grid(row=0, column=1)
Label(gn_wn, text=" Enter a minimum value: ").place(x=295, y=100)
entry_min = Entry(gn_wn)
entry_min.place(x=450, y=100)
Label(gn_wn, text=" Enter a maximum value: ").place(x=295, y=200)
entry_max = Entry(gn_wn)
entry_max.place(x=450, y=200)
Label(gn_wn, text="Random value is: ").place(x=40, y=40)
def generate_number():
min_ = int(entry_min.get())
max_ = int(entry_max.get())
random_num = random.randint(min_, max_)
d_rn = Label(gn_wn, text=random_num)
d_rn.config(font=("Yu Gothic UI", 14))
d_rn.place(x=40, y=80)
Button(gn_wn, text="Generate", padx=220, pady=25, command=generate_number).place(x=25, y=280)
gn_wn.mainloop()
def open_coin():
c_wn = Tk()
c_wn.title("Random App - Flip a Coin")
c_wn.geometry("600x400")
c_wn.resizable(False, False)
Label(c_wn, text=" ").grid(row=0,
column=0)
Label(c_wn, text="Flip the coin below!", font=("Yu Gothic UI", 12)).grid(row=0, column=1)
Label(c_wn, text=' ').grid(row=1, column=1)
coin_label = Label(c_wn, text="")
coin_label.place(relx=0.5, rely=0.2, anchor='s')
def flip():
coin_values = ["Heads", "Tails"]
coin_face = random.choice(coin_values)
if coin_face == "Heads":
coin_label.config(text="Coin: Heads")
else:
coin_label.config(text="Coin: Tails")
coin = Button(c_wn, text='coin', padx=100, pady=90, command=flip)
coin.place(relx=0.5, rely=0.5, anchor=CENTER)
c_wn.mainloop()
def open_average():
avg_wn = Tk()
avg_wn.title("Random App - Averages")
avg_wn.geometry("840x300")
Label(avg_wn, text=" ").grid(row=0, column=0)
avg_instruct = Label(avg_wn, text="Enter your values below to get the averages in mean, median, and mode(put a "
"space between commas")
avg_instruct.config(font=("Yu Gothic UI", 10))
avg_instruct.grid(row=0, column=1)
Label(avg_wn, text=" ").grid(row=1, column=0)
entry = Entry(avg_wn)
entry.grid(row=2, column=1)
def calculate():
list_data = entry.get().split(', ')
list_data = [float(i) for i in list_data]
mean = sum(list_data) / len(list_data)
Label(avg_wn, text='Mean').grid(row=5, column=0)
Label(avg_wn, text=str(mean)).grid(row=6, column=0)
list_data_len = len(list_data)
list_data.sort()
if list_data_len % 2 == 0:
median1 = list_data[list_data_len // 2]
median2 = list_data[list_data_len // 2 - 1]
median = (median1 + median2) / 2
else:
median = list_data[list_data_len // 2]
Label(avg_wn, text='Median: ').grid(row=5, column=1)
Label(avg_wn, text=median).grid(row=6, column=1)
list_data_for_mode = Counter(list_data)
get_mode = dict(list_data_for_mode)
mode = [k for k, v in get_mode.items() if v == max(list(list_data_for_mode.values()))]
if len(mode) == list_data_len:
get_mode = ["No mode found"]
else:
get_mode = [str(i) for i in mode]
Label(avg_wn, text="Mode: ").grid(row=5, column=2)
Label(avg_wn, text=get_mode[0]).grid(row=6, column=2)
Label(avg_wn, text=" ").grid(row=3, column=0)
Button(avg_wn, text='Enter', command=calculate).grid(row=4, column=1)
Label(root, text=" ").grid(row=0, column=0)
title = Label(root, text="Welcome to Random")
title.config(font=("Yu Gothic UI", 24))
title.grid(row=0, column=1)
button1 = Button(root, text="Generate a random number", padx=80, pady=25, command=open_gn)
button1.place(x=2.25, y=100)
button2 = Button(root, text="Calculate mean, mode, median, and range", padx=20, pady=25, command=open_average)
button2.place(x=325, y=100)
button3 = Button(root, text="Flip a Coin", padx=125, pady=25, command=open_coin)
button3.place(x=2.25, y=200)
button4 = Button(root, text="Create a graph to analyze", padx=66, pady=25)
button4.place(x=325, y=200)
root.mainloop()
I am trying to make an application that can do a bunch of statistics-related stuff and in it, I am trying to make a function that can generate a random number(go to the def open_gn() part. Thats where the error is.) However, when I try to run it, the program returns an error saying:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\redde\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:/Learn_python (2)/random app/main.py", line 37, in generate_number
random_num = random.randint(min_, max_)
AttributeError: module 'random' has no attribute 'randint'
I tried copying and pasting the code where I use the randint attribute but it also recieved an error. Please help.
Did you happen to name your Python script random.py? This thread suggests that that might be the cause of your issue. If it is, rename the script to something that is not a keyword and try again (for example, random_app.py).

My Tkinter Label for calculating mode is returning "N." Why is this and how do I fix this?

from tkinter import *
import random
from collections import Counter
root = Tk()
root.title("Random")
root.geometry("600x400")
root.resizable(False, False)
def open_saw():
saw_wn = Tk()
saw_wn.title("Random App - Spin a Wheel")
saw_wn.geometry("600x400")
saw_wn.resizable(False, False)
saw_wn.mainloop()
def open_coin():
c_wn = Tk()
c_wn.title("Random App - Flip a Coin")
c_wn.geometry("600x400")
c_wn.resizable(False, False)
Label(c_wn, text=" ").grid(row=0, column=0)
Label(c_wn, text="Flip the coin below!").grid(row=0, column=1)
c_wn.mainloop()
def open_average():
avg_wn = Tk()
avg_wn.title("Random App - Averages")
avg_wn.geometry("800x400")
avg_wn.resizable(False, False)
Label(avg_wn, text=" ").grid(row=0, column=0)
Label(avg_wn, text="Enter your values below to get the averages in mean, median, and mode.(put a space between "
"commas)").grid(row=0, column=1)
Label(avg_wn, text=" ").grid(row=1, column=0)
entry = Entry(avg_wn)
entry.grid(row=2, column=1)
def calculate():
list_data = entry.get().split(', ')
list_data = [float(i) for i in list_data]
mean = sum(list_data) / len(list_data)
Label(avg_wn, text='Mean: ' + str(mean)).grid(row=5, column=0)
list_data_len = len(list_data)
list_data.sort()
if list_data_len % 2 == 0:
median1 = list_data[list_data_len // 2]
median2 = list_data[list_data_len // 2 - 1]
median = (median1 + median2) / 2
else:
median = list_data[list_data_len // 2]
Label(avg_wn, text='Median: ' + str(median)).grid(row=5, column=1)
list_data_for_mode = Counter(list_data)
get_mode = dict(list_data_for_mode)
mode = [k for k, v in get_mode.items() if v == max(list(list_data_for_mode.values()))]
if len(mode) == list_data_len:
get_mode = "No mode found"
else:
get_mode = [str(i) for i in mode]
Label(avg_wn, text=get_mode[0]).grid(row=5, column=2)
Label(avg_wn, text=" ").grid(row=3, column=0)
Button(avg_wn, text='Enter', command=calculate).grid(row=4, column=1)
Label(root, text=" ").grid(row=0, column=0)
title = Label(root, text="Welcome to Random")
title.config(font=("Yu Gothic UI", 24))
title.grid(row=0, column=1)
button1 = Button(root, text=" Spin a wheel ", padx=80, pady=25, command=open_saw)
button1.place(x=2.25, y=100)
button2 = Button(root, text="Calculate mean, mode, median, and range", padx=20, pady=25, command=open_average)
button2.place(x=325, y=100)
button3 = Button(root, text="Flip a Coin", padx=125, pady=25, command=open_coin)
button3.place(x=2.25, y=200)
button4 = Button(root, text="Roll a die", padx=107.5, pady=25)
button4.place(x=325, y=200)
root.mainloop()
I am making an application that can do simple statistics problems. I am currently working on the one that calculates mode, mean, and median. The mean and median were displayed properly in their spots, but the mode was not. It displays an "N" which I don't know why it is doing that. Please tell me how to fix it and please tell me what it is and what it means as I want to learn from it.
It is because when len(mode) == list_data_len is True, get_mode will be assigned "No mode found". So text=get_mode[0] will assign "N" to the label. get_mode = ["No mode found"] should be used instead:
def calculate():
...
if len(mode) == list_data_len:
get_mode = ["No mode found"]
else:
get_mode = [str(i) for i in mode]
mode_label.config(text=get_mode[0])

Trying to save values from tkInter scale

This is my first post so please have patience
I've got a school assignment to create an art supplies application and I've drawn a blank why my tkinter scale values are not saving to a file.
The customer details and submit button code works as expected (saves to a file = info.txt)
The Order tab page doesn't work as expected = does not append info.txt with specific quantities of art supplies ordered
Here's my code
#def mainmenu():
from tkinter import *
from tkinter import ttk
import re
NON_ALPHA_RE = re.compile('[^A-Z0-9]+')
POSTCODE_RE = re.compile('^[A-Z]{1,2}[0-9]{1,2}[A-Z]? [0-9][A-Z]{2}$')
def normalise_postcode(eZIP_Postalcode):
eZIP_Postalcode = NON_ALPHA_RE.sub('', eZIP_Postalcode.upper())
eZIP_Postalcode = eZIP_Postalcode[:-3] + ' ' + eZIP_Postalcode[-3:]
if POSTCODE_RE.match(eZIP_Postalcode):
return eZIP_Postalcode
return None
def submit() :
invalidtext_1.set("")
invalidtext_2.set("")
invalidtext_3.set("")
invalidtext_4.set("")
invalidtext_5.set("")
eName =Name.get()
eSurname =Surname.get()
ecountry =country.get()
ecity =city.get()
eAddressLine1 = AddressLine1.get()
eAddressLine2 = AddressLine2.get()
eState_Province_Region = State_Province_Region.get()
eZIP_Postalcode = ZIP_Postalcode.get()
valid = True
if eName.isalpha() == False:
invalidtext_1.set("Invalid forename. Please use letters only.")
valid = False
if eSurname.isalpha() == False:
invalidtext_2.set("Invalid surname. Please use letters only.")
valid = False
if ecountry.isalpha() == False:
invalidtext_3.set("Invalid country name. Please use letters only.")
valid = False
if ecity.isalpha() == False:
invalidtext_4.set("Invalid city name. Please use letters only.")
valid = False
if eZIP_Postalcode != normalise_postcode(eZIP_Postalcode):
invalidtext_5.set("Please enter a valid postcode.")
valid = False
if valid == False:
return
else:
eName = eName.ljust(150)
eSurname = eSurname.ljust(150)
ecountry = ecountry.ljust(150)
ecity = ecity.ljust(150)
eAddressLine1 = eAddressLine1.ljust(150)
eAddressLine2 = eAddressLine2.ljust(150)
eState_Province_Region = eState_Province_Region.ljust(150)
eZIP_Postalcode = eZIP_Postalcode.ljust(150)
fileObject = open("Info.txt","a")
fileObject.write(eName +"\n" + eSurname +"\n" + ecountry +"\n" + ecity +"\n" + eAddressLine1 +"\n" + eAddressLine2 +"\n" + eState_Province_Region +"\n" + eZIP_Postalcode +"\n")
fileObject.close()
return
def submitNumber():
Paint=Paint.get()
Paper=Paper.get()
PaintBrush =PaintBrush.get()
Easles=Easles.get()
Pencils=Pencils.get()
Paint = Paint.ljust(150)
Paper = Paper.ljust(150)
PaintBrush = PaintBrush.ljust(150)
Easles = Easles.ljust(150)
Pencils = Pencils.ljust(150)
fileObject = open("Info.txt","a")
fileObject.write(paint + paper + paintbrush + Easles + pencils +"\n")
fileObject.close()
def mainWindow():
global Name, invalidtext_1, frame1, invalidtext_2,Surname,city,country,invalidtext_3,invalidtext_4,AddressLine1,AddressLine2,State_Province_Region,ZIP_Postalcode,invalidtext_5
window=Tk()
window.title("Artist Products")
window.configure(background = "#800000")
window.resizable(width=True, height=True)
# DON'T NEED window.geometry("500x300") #Width x Height
tab_control = ttk.Notebook(window)
tab1 = ttk.Frame(tab_control)
#Tab 1 (as in the number 1!)
tab_control.add(tab1, text='Customer details')
Label (tab1, text="Name:" , bg="#800", fg="white", font="futuran 12").grid(row=1, column=0)
Name=StringVar()
eName=Entry(tab1, textvariable=Name)
eName.grid(row=1, column=1)
invalidtext_1=StringVar()
invalid_1= Label(tab1, textvariable=invalidtext_1, font="Helvetica 12 ", fg="red")
invalid_1.grid(row=1,column=2, sticky=W)
Label (tab1, text="Surname:" , bg="#800", fg="white", font="futuran 12").grid(row=2, column=0)
Surname=StringVar()
eSurname=Entry(tab1, textvariable=Surname)
eSurname.grid(row=2, column=1)
invalidtext_2=StringVar()
invalid_2= Label(tab1, textvariable=invalidtext_2, font="Helvetica 12 ", fg="red")
invalid_2.grid(row=2,column=2, sticky=W)
Label (tab1, text="Adress Line 1:" , bg="#800", fg="white", font="futuran 12").grid(row=3, column=0)
AddressLine1=StringVar()
eAddressLine1=Entry(tab1, textvariable=AddressLine1)
eAddressLine1.grid(row=3, column=1)
Label (tab1, text="Adress Line 2:" , bg="#800", fg="white", font="futuran 12").grid(row=4, column=0)
AddressLine2=StringVar()
eAddressLine2=Entry(tab1, textvariable=AddressLine2)
eAddressLine2.grid(row=4, column=1)
Label (tab1, text="State/province/region:" , bg="#800", fg="white", font="futuran 12").grid(row=5, column=0)
State_Province_Region=StringVar()
eState_Province_Region=Entry(tab1, textvariable=State_Province_Region)
eState_Province_Region.grid(row=5, column=1)
Label (tab1, text="ZIP/postal code:" , bg="#800", fg="white", font="futuran 12").grid(row=6, column=0)
ZIP_Postalcode=StringVar()
eZIP_Postalcode=Entry(tab1, textvariable=ZIP_Postalcode)
eZIP_Postalcode.grid(row=6, column=1)
invalidtext_5=StringVar()
invalid_5= Label(tab1, textvariable=invalidtext_5, font="Helvetica 12 ", fg="red")
invalid_5.grid(row=6,column=2, sticky=W)
Label (tab1, text="Country name:" , bg="#800", fg="white", font="futuran 12").grid(row=7, column=0)
country=StringVar()
ecountry=Entry(tab1, textvariable=country)
ecountry.grid(row=7, column=1)
invalidtext_3=StringVar()
invalid_3= Label(tab1, textvariable=invalidtext_3, font="Helvetica 12 ", fg="red")
invalid_3.grid(row=7,column=2, sticky=W)
Label (tab1, text="City:" , bg="#800", fg="white", font="futuran 12").grid(row=8, column=0)
city=StringVar()
ecity=Entry(tab1, textvariable=city)
ecity.grid(row=8, column=1)
invalidtext_4=StringVar()
invalid_4= Label(tab1, textvariable=invalidtext_4, font="Helvetica 12 ", fg="red")
invalid_4.grid(row=8,column=2, sticky=W)
####Tab 2
tab2 = ttk.Frame(tab_control)
tab_control.add(tab2, text='View All Products')
Label (tab2, text='Paper(50 pages non lined):£3',bg="#800", fg="white", font="futuran 12").grid(row=1, column=0)
Paper = Scale(tab2, from_=0, to=100, orient=HORIZONTAL)
Paper.grid(row=1, column=1)
Label (tab2, text='Paint (acrylic):£6' ,bg="#800", fg="white", font="futuran 12").grid(row=2, column=0)
Paint = Scale(tab2, from_=0, to=100, orient=HORIZONTAL)
Paint.grid(row=2, column=1)
Label (tab2, text='Paint brush:£4' ,bg="#800", fg="white", font="futuran 12").grid(row=3, column=0)
PaintBrush = Scale(tab2, from_=0, to=100, orient=HORIZONTAL)
PaintBrush.grid(row=3, column=1)
Label (tab2, text='Easels:£6' ,bg="#800", fg="white", font="futuran 12").grid(row=4, column=0)
Easels = Scale(tab2, from_=0, to=100, orient=HORIZONTAL)
Easels.grid(row=4, column=1)
Label (tab2, text='Pencils:£4.50' ,bg="#800", fg="white", font="futuran 12").grid(row=5, column=0)
Pencils = Scale(tab2, from_=0, to=100, orient=HORIZONTAL)
Pencils.grid(row=5, column=1)
#Tab 3
tab3 = ttk.Frame(tab_control)
tab_control.add(tab3, text='Invoices')
tab_control.grid(row=1, column=1)
#Tab 4
tab4 = ttk.Frame(tab_control)
tab_control.add(tab4, text='Basket')
tab_control.grid(row=1, column=1)
Label (tab4, text="Basket",bg="#800", fg="white", font="futuran 12").grid(row=1, column=0)
#Tab 5
tab5 = ttk.Frame(tab_control)
tab_control.add(tab5, text='Orders')
tab_control.grid(row=1, column=1)
#buttons
b6=Button(tab1, text="Close",command=quit, width=10)
b6.grid(row=12, column=0)
b6=Button(tab2, text="Close",command=quit, width=10)
b6.grid(row=12, column=0)
b6=Button(tab3, text="Close",command=quit, width=10)
b6.grid(row=12, column=0)
b6=Button(tab4, text="Close",command=quit, width=10)
b6.grid(row=12, column=0)
b6=Button(tab5, text="Close",command=quit, width=10)
b6.grid(row=12, column=0)
b18= Button(tab1, text=" Submit ",command=submit,width=10)
b18.grid(row=12, column=1)
b17= Button(tab2, text=" Submit ",command=submit,width=10)
b17.grid(row=12, column=1)
frame2 = Frame(window)
frame2.grid()
return window
window = mainWindow()
window.mainloop()
mainWindow()
I've also tried to get the customer details submit button to save to the file and then close down the customer details tab or ar least move the focus to the 'View all products' tab (so that the user can then concentrate on their order).
Help!
It looks like your problem is one of variable names. You are clobbering the scale object with the result of a call to get(), but then you write to what I assume was the variable you intended to assign. That variable is never initialized and is therefore None, so nothing is written to the file.
e.g.
Paint = Paint.get()
...
Paint = Paint.ljust(150)
...
fileObject.write(... + paint + ...)
should be
paint = Paint.get()
...
paint = Paint.ljust(150)
...
fileObject.write(... + paint)

Using StringVar data as a list

I've been following this website for a while. It is really helpful. So, thanks for all the useful tips.
I've been searching for this answer for the past two weeks without any success, so now I'm compelled to ask out of total frustration with my current obstacle.
How do you use StringVar as a list?
Basically, I was coding the following program for my wife. The code is pretty messy as it is my first program I've tried to code.
The idea was that I would take 3 variables; password, secret number and website and then do some work on them using if statements and lists to create a unique password.
First problem was that I couldn't restrict the character length of the entry widgets but in the end i solved that but i still want to limit the characters that can be input.
for instance in the website entry box, i want to allow only letters.
If I could convert StringVar to a list, I could do some work with messy if statements to allow only certain characters in each index but everythime i try it says that stringvars cant be used as a list.
I need them as a list to limit the type of characters that can be entered and also so that i can do work on the variables to get the final output.
CODE:
from Tkinter import *
import Tkinter
from PIL import Image, ImageTk
import os
Title= ("Helvetica", 20, "bold", "underline")
Heading= ("Courier", 20, "bold")
Body= ("Courier", 15)
Body1= ("Courier", 15, "bold")
notice= ("Courier", 10)
Body2= ("Courier", 15, "bold", "underline")
root = Tk()
root.title("Koala Series: Encrypter")
root.configure(background="#ffefd5")
root.geometry('{}x{}'.format(510, 600))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1) # not needed, this is the default behavior
root.rowconfigure(1, weight=1)
root.rowconfigure(2, weight=1)
website = StringVar()
Titlemsg = Label(root, text="Koala Encrypter", font=Title, bg="#00FA9A", relief=RAISED,)
Titlemsg.grid( row=7, pady=25, sticky=N+S+E+W)
img1 = ImageTk.PhotoImage(Image.open("koala.jpeg"))
startpic = Label(root, image = img1, relief=RIDGE )
startpic.grid( row=10,pady=25, )
Head = Label(root,anchor=CENTER,text="Welcome to the Koala Encrypter \n\n A Koala series tool that allows you\n\n to Encrypt your passwords \n\n Click \'Start Encrypting\' to continue \n\n", font=Body, bg="#ffefd5", relief=RAISED,)
Head.grid( row=14, pady=25, columnspan=2, sticky=N+S+E+W)
web = Label(root, text="WEBSITE: ", font=Body, bg="#ffefd5", justify=CENTER,)
#website.set("Enter your website here")
entry = Entry(root,textvariable=website , justify=CENTER,relief=SUNKEN,cursor="pencil", takefocus=True )
Notice1 = Label( text="Please only insert the first 5 letters of the website!!",font=notice, bg="#ffefd5", fg="#0000ff",)
passw = Label(root, text="PASSWORD: ", font=Body, bg="#ffefd5", justify=CENTER)
passwordvar= StringVar()
entry1 = Entry(root, textvariable= passwordvar, justify=CENTER,relief=SUNKEN, cursor="pencil", takefocus=True )
Notice= Label(root, text="Your password must only be 5 characters long!!", font=notice, bg="#ffefd5", fg="#0000ff", justify=CENTER)
def callback(event):
if "<0>":
top = Toplevel(bg="#ffefd5")
top.title("Koala Encrypter")
popuptitle = Label(top, text="Your secret number must be between 1 and 9:", font=Body1, fg="red", bg="#ffefd5")
popuptitle.grid(row = 2,column=0, padx=5, pady = 50,sticky=N+S+E+W)
secret = Label(root, text="SECRET NUMBER: ", font=Body, bg="#ffefd5" , justify=CENTER,)
numbervar = StringVar()
entry2 = Entry(root, textvariable=numbervar , justify=CENTER,relief=SUNKEN,cursor="pencil", takefocus=True)
entry2.bind("<0>", callback)
Notice2 = Label(root, text="your secret number must be between 1 and 9!!!", font=notice, bg="#ffefd5", fg="#0000ff", justify=CENTER)
img = ImageTk.PhotoImage(Image.open("Koalalogo.jpg"))
panel = Label(root, image = img, relief=SUNKEN)
correct= Label(root, text="Check the below details \n\n Click \'yes\' if they are correct \n\n Click \'No\' to go back \n\n", font=Body1, bg="#ffefd5")
yourwebsite = Label(root, text="The Website is :", font=Body, bg="#ffefd5")#
website1 = Label(root, font=Body2, bg="#ffefd5",fg= "#00009C", textvariable = website)#
yourpassword = Label(root, text="Your Password is:", font=Body, bg="#ffefd5")
yournumber1= Label(root, font=Body2, bg="#ffefd5",textvariable = numbervar , fg= "#00009C", )
yourpassword1 = Label(root, font=Body2, bg="#ffefd5",textvariable = passwordvar , fg= "#00009C", )
yournumber= Label(root, text="Your Secret Number is:", font=Body, bg="#ffefd5")
def restart():
Titlemsg.grid_forget()
correct.grid_forget()
yourwebsite.grid_forget()
website1.grid_forget()
yourpassword.grid_forget()
yourpassword1.grid_forget()
yournumber.grid_forget()
yournumber1.grid_forget()
panel.grid_forget()
toolbar.grid_forget()
yes.grid_forget()
no.grid_forget()
entry.delete(0,END)
entry1.delete(0,END)
entry2.delete(0,END)
Titlemsg.grid( row=7, pady=25, sticky=N+S+E+W)
startpic.grid( row=10,pady=25, )
Head.grid( row=14, pady=25, columnspan=2, sticky=N+S+E+W)
toolbar.grid( row=21, )
end.grid(column =3, row=1, sticky=N+S+E+W)
begin.grid(column =2, row=1, sticky=N+S+E+W)
def start():
#entry.destroy()
#entry1.destroy()
#entry2.destroy()
toolbar.grid_forget()
Titlemsg.grid_forget()
begin.grid_forget()
Head.grid_forget()
startpic.grid_forget()
web.grid(row=3, column=0, sticky= W+E)
entry.grid( row=3, column=1, padx=50)
passw.grid(row=10, column=0)
Notice1.grid(row=4, sticky=N+S+E+W, columnspan=2)
entry1.grid(row=10, column=1)
Notice.grid(row=11,column=0, columnspan=2,)
secret.grid(row=13, column=0)
entry2.grid( row=13, column=1)
Notice2.grid( row=14,column=0, columnspan=2,)
panel.grid(row=20,columnspan=2, pady=70)
confirm.grid(column =1, row=1)
reset.grid(column =2, row=1)
end.grid(column =3, row=1)
toolbar.grid(row=21, column=0, columnspan=2)
Titlemsg.grid(row=0, column=0, columnspan=2, sticky=E+W)
def Reset():
entry.delete(0,END)
entry1.delete(0,END)
entry2.delete(0,END)
def clear_text():
#entry.destroy()
#entry1.destroy()
#entry2.destroy()
panel.grid_forget()
entry.grid_forget()
entry1.grid_forget()
entry2.grid_forget()
web.grid_forget()
Notice.grid_forget()
passw.grid_forget()
secret.grid_forget()
Notice1.grid_forget()
Notice2.grid_forget()
confirm.grid_forget()
reset.grid_forget()
toolbar.grid_forget()
Titlemsg.grid_forget()
Titlemsg.grid(row=0, column=0, columnspan=2, sticky=E+W)
correct.grid(row=1, column=0, columnspan=2, sticky=E+W)
yourwebsite.grid(row=2,column=0,sticky=E+W, pady=5)
website1.grid(row=2, column=1, padx=65,sticky=E+W, pady=5)
yourpassword.grid(row=4, column=0,sticky=E+W, pady=5)
yourpassword1.grid(row=4, column=1, padx=65,sticky=E+W, pady=5)
yournumber.grid(row=6, column=0,sticky=E+W, pady=5)
yournumber1.grid(row=6, column=1, padx=65,sticky=E+W, pady=5)
panel.grid(row=8, column=0, columnspan=2, pady=50)
toolbar.grid(row=10, column=0, columnspan=2)
yes.grid(column =1, row=1)
no.grid(column =2, row=1)
def popup():
top = Toplevel(bg="#ffefd5")
top.title("Koala Encrypter")
popuptitle = Label(top, text="Your password is:", font=Body1, fg="red", bg="#ffefd5")
popuptitle.grid(row = 2,column=0, padx=5, pady = 50,sticky=N+S+E+W)
pwd= Label(top, font=Body2, text="password", bg="#ffefd5", fg= "#00009C", ) #textvariable = newpassword ,
pwd.grid(row= 2, column=1,sticky=E+W,padx=15)
button = Button(top, text="OK", command=top.destroy, relief=RAISED )
button.grid(column =0,columnspan=2, row=4, sticky=N+S+E+W)
def helpmsg():
top = Toplevel(bg="#ffefd5")
top.title("Koala Encrypter")
popuptitle = Label(top, text="Koala series 1.0 - Koala Encrypter", font=Title, bg="#00FA9A", relief=RAISED,)
popuptitle.grid(row = 2,column=0, padx=5, pady = 50,sticky=N+S+E+W)
pwd= Label(top, font=Body, text="Free software to help you keep your acounts safe", bg="#ffefd5")
pwd.grid(row= 1,sticky=E+W,)
Titlems = Label(top, text="Koala Encrypter", font=Title, bg="#00FA9A", relief=RAISED,)
Titlems.grid( row=0, pady=25, sticky=N+S+E+W)
button = Button(top, text="OK", command=top.destroy, relief=RAISED )
button.grid(column =0,columnspan=2, row=4, sticky=N+S+E+W)
max_len = 5
def on_write(*args):
s = website.get()
if len(s) > max_len:
website.set(s[:max_len])
website.trace_variable("w", on_write)
max_len1 = 5
def on_write(*args):
s = passwordvar.get()
if len(s) > max_len1:
passwordvar.set(s[:max_len1])
passwordvar.trace_variable("w", on_write)
max_len2 = 1
def on_write(*args):
s = numbervar.get()
if len(s) > max_len2:
numbervar.set(s[:max_len2])
numbervar.trace_variable("w", on_write)
toolbar = Frame(root)
reset = Button(toolbar, text="Reset", width=6, command=Reset, cursor="cross", relief=RAISED, takefocus=True )
end = Button(toolbar, text="Quit" ,command=root.destroy, relief=RAISED, cursor="X_cursor", takefocus=True)
end.grid(column =3, row=1, sticky=N+S+E+W)
begin = Button(toolbar, text="Start Encrypting", command=start, relief=RAISED, cursor="star",takefocus=True )
begin.grid(column =2, row=1, sticky=N+S+E+W)
confirm = Button(toolbar, text="Next", command =clear_text, cursor="star", relief=RAISED,takefocus=True )
yes = Button(toolbar, text="Yes", command =popup, cursor="star", relief=RAISED,takefocus=True )
no = Button(toolbar, text="No", command =restart, cursor="pirate", relief=RAISED, takefocus=True )
toolbar.grid( row=21, )
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Restart", command=restart)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.destroy)
helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu, )
helpmenu.add_command(label="About...", command=helpmsg)
app = root
root.mainloop()
# add functionality, fix validation
To restrict the type/number of characters that can be typed into an entry widget, you can use the entry validatecommand. Here is an example to allow only letters and another one to restrict the entry to 4 digits:
from tkinter import Tk, Entry, Label
def only_letters(action, char):
if action == "1":
# a character is inserted (deletion is 0) allow the insertion
# only if the inserted character char is a letter
return char.isalpha()
else:
# allow deletion
return True
def only_numbers_max_4(action, new_text):
if action == "1":
return new_text.isdigit() and len(new_text) <= 4
else:
return True
root = Tk()
# register validate commands
validate_letter = root.register(only_letters)
validate_nb = root.register(only_numbers_max_4)
Label(root, text="Only letters: ").grid(row=0, column=0)
e1 = Entry(root, validate="key", validatecommand=(validate_letter, '%d', '%S'))
# %d is the action code and %S the inserted/deleted character
e1.grid(row=0, column=1)
Label(root, text="Only numbers, at most 4: ").grid(row=1, column=0)
e2 = Entry(root, validate="key", validatecommand=(validate_nb, '%d', '%P'))
# %P is the new content of the entry after the modification
e2.grid(row=1, column=1)
root.mainloop()
For more details on entry validation, see http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/entry-validation.html

Categories

Resources