PRNG, python. 1 button - 2 function? - python

help me please. It is necessary that when the 'Generate' button(gen) is pressed, 2 functions (clicked1, gen1) are executed. But it only run clicked1.
I read that I can use lambda; or create a separate function that includes the ones you need. But gen1 still fails.
but the most important thing is that
when I removed clicked1 from the code completely, then gen1 didn't work either(
import tkinter
from tkinter import *
from tkinter import messagebox, scrolledtext
from tkinter.ttk import Progressbar
from tkinter import ttk
from PIL import Image, ImageTk
from random import randint
class App:
def __init__(self):
self.window = tkinter.Tk()
self.window.title("Генератор")
self.window['bg'] = '#FFF5EE'
self.window.geometry('660x550')
self.window.resizable(False,False)
self.lb1 = Label(self.window, text="Enter:", background='#FFF5EE', font = ("Comic Sans MS", 14))
self.lb1.grid(column=0, row=2)
self.lb2 = Label(self.window, text="min(1-999)",background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb2.grid(column=1, row=3)
self.lb3 = Label(self.window, text="max(1-999)", background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb3.grid(column=1, row=4)
self.lb4 = Label(self.window, text="amount of numbers", background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb4.grid(column=4, row=3)
self.txt2 = Entry(self.window,width=10, borderwidth=3)
self.txt2.grid(column=2, row=3)
self.txt3 = Entry(self.window,width=10, borderwidth=3)
self.txt3.grid(column=2, row=4)
self.txt4 = Entry(self.window,width=10, borderwidth=3)
self.txt4.grid(column=5, row=3)
self.scrolltxt = scrolledtext.ScrolledText(self.window, width=30, height=3, borderwidth=7, state='disabled')
self.scrolltxt.grid(row=1, column=2, columnspan=3, padx=10, pady=10)
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\11.png")
self.photo = ImageTk.PhotoImage(self.image)
self.gen = Button(self.window, text="Generate", command = lambda:[self.clicked1(), self.gen1()])
self.gen.grid(row=4, column=6)
self.canvas = tkinter.Canvas(self.window, height=250, width=230)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw', image = self.photo)
self.btn = Button(self.window, text="Delete", command=self.delete)
self.btn.grid(column=6, row=5)
self.exit = Button(self.window, text="Exit", command=quit)
self.exit.grid(column=6, row=6)
self.window.mainloop()
def clicked1(self):
print("clicked1")
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\22.png")
self.photo = ImageTk.PhotoImage(self.image)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw',image=self.photo)
def gen1(self):
try:
MinNum = int(self.txt2.get())
MaxNum = int(self.txt3.get())
Num = int(self.txt4.get())
except ValueError:
messagebox.showerror("Error", "Please enter correct numbers!")
else:
Nums = " "
if MinNum <= MaxNum:
i = 0
while i < Num:
numOne = randint(MinNum, MaxNum)
Nums = Nums + ' ' + str(numOne)
i += 1
self.scrolltxt.delete(1.0, END)
self.scrolltxt.insert(INSERT, str(Nums) + "\n")
else:
messagebox.showerror("Error", "Please enter correct numbers!")
def delete(self):
self.scrolltxt.delete(1.0, END)
print("clicked1")
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\11.png")
self.photo = ImageTk.PhotoImage(self.image)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw',image=self.photo)
app= App()
I don't understand what I'm doing wrong
I hope I explained the problem clearly

Both the clicked1() and gen1() are executed when the Generate button is clicked. However nothing will be inserted into the text box because the text box is disabled.
You need to enable the text box before inserting text and disabled it back after:
self.scrolltxt.config(state="normal") # enable the text box
self.scrolltxt.delete("1.0", END) # better use "1.0" instead of 1.0
self.scrolltxt.insert(INSERT, str(Nums) + "\n")
self.scrolltxt.config(state="disabled") # disable the text box

Related

I want to display data from mongoDB to treeview in Python tkinter

I saw this video: https://www.youtube.com/watch?v=W0l0r0PekvM&t=20s
The code could display data but it display by many Grid together so i can not create a Scrollbar.
you can see the function display data in CRUD() -> creategrid(n)
sorry for my bad English ^^
my code:
from tkinter import *
import tkinter as tk
from tkinter import ttk
import pymongo
from tkinter import messagebox
from tkinter import filedialog
from PIL import Image, ImageTk
import pybase64 as base64
import gridfs
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["enrollmentsystem"] #database file
mycol = mydb["employees"]
mycol2 = mydb["fs.files"]
def CRUD():
lst=[["ID","Name","Age","Departure","Gender","Skill","Working (Y)","Trained (Y)","Salary"]]
window=tk.Toplevel(w1)
window.title("UPDATE PROFILE")
window.geometry('300x400')
window.configure(bg="bisque2")
window3=tk.Toplevel(window)
window3.title("UPDATE PROFILE")
window3.geometry('+%d+%d' % (100,100))
window3.configure(bg="bisque2")
def callback(event):
global lstindex
li=[]
li=event.widget._values
lstindex=li[1]
cid.set(lst[li[1]][0])
cname.set(lst[li[1]][1])
cage.set(lst[li[1]][2])
cdept.set(lst[li[1]][3])
cgender.set(lst[li[1]][4])
cskill.set(lst[li[1]][5])
cwyear.set(lst[li[1]][6])
ctyear.set(lst[li[1]][7])
csalary.set(lst[li[1]][8])
def creategrid(n):
lst.clear()
lst.append(["ID","Name","Age","Departure","Gender","Skill","Working (Y)","Trained (Y)","Salary"])
cursor = mycol.find({})
for text_fromDB in cursor:
empid=str(text_fromDB["empid"])
empname=str(text_fromDB["empname"].encode('utf-8').decode('utf-8'))
empage=str(text_fromDB["empage"].encode('utf-8').decode('utf-8'))
empdept=str(text_fromDB["empdept"].encode('utf-8').decode('utf-8'))
empgender=str(text_fromDB["empgender"].encode('utf-8').decode('utf-8'))
empskill=str(text_fromDB["empskill"].encode('utf-8').decode('utf-8'))
empwyear=int(text_fromDB["empwyear"].encode('utf-8').decode('utf-8'))
emptyear=int(text_fromDB["emptyear"].encode('utf-8').decode('utf-8'))
empsalary=float(text_fromDB["empsalary"].encode('utf-8').decode('utf-8'))
lst.append([empid,empname,empage,empdept,empgender,empskill,empwyear,emptyear,empsalary])
for i in range(len(lst)):
for j in range(len(lst[0])):
mgrid=tk.Entry(window3,width=10)
mgrid.insert(tk.END, lst[i][j])
mgrid._values =mgrid.get(),i
mgrid.grid(row=i+12,column=j+11)
mgrid.bind("<Button-1>",callback)
if n==1:
for label in window.grid_slaves():
if int(label.grid_info()["row"]) >11:
label.grid_forget()
def msgbox(msg,titlebar):
result = messagebox.askokcancel(title=titlebar, message=msg)
return result
def save():
r=msgbox("save record?","record")
if r==True:
newid = mycol.count_documents({})
if newid!=0:
newid = mycol.find_one(sort=[("empid", -1)])["empid"]
id=newid+1
cid.set(id)
mydict = {"empid": int(custid.get()),"empname":custname.get(), "empage":custage.get(),
"empdept":custdept.get(),"empgender":custgender.get(),"empskill":custskill.get(),
"empwyear":custwyear.get(),"emptyear":custtyear.get(),"empsalary":custsalary.get()}
x = mycol.insert_one(mydict)
messagebox.showinfo("info", "save completed, please add photo")
creategrid(1)
creategrid(0)
def delete():
r=msgbox("Delete?", "record")
if r ==True:
myquery = {"empid":int(custid.get())}
mycol.delete_one(myquery)
creategrid(1)
creategrid(0)
def update():
r=msgbox("Update?","record")
if r ==True:
myquery={"empid":int(custid.get())}
newvalues={"$set":{"empname":custname.get()}}
mycol.update_one(myquery,newvalues)
newvalues={"$set":{"empage":custage.get()}}
mycol.update_one(myquery,newvalues)
newvalues={"$set":{"empdept":custdept.get()}}
mycol.update_one(myquery,newvalues)
newvalues={"$set":{"empgender":custgender.get()}}
mycol.update_one(myquery,newvalues)
newvalues={"$set":{"empskill":custskill.get()}}
mycol.update_one(myquery,newvalues)
newvalues={"$set":{"empwyear":custwyear.get()}}
mycol.update_one(myquery,newvalues)
newvalues={"$set":{"emptyear":custtyear.get()}}
mycol.update_one(myquery,newvalues)
newvalues={"$set":{"empsalary":custsalary.get()}}
mycol.update_one(myquery,newvalues)
creategrid(1)
creategrid(0)
def upload_file(): # Image upload and display
global filename,img, fs
f_types =[('Png files','*.png'),('Gif Files', '*.gif'),('PMG files','*.pmg'),('jpg files','*.jpg')]
filename = filedialog.askopenfilename(filetypes=f_types,defaultextension='.png')
img=Image.open(filename)
img=img.resize((150,150)) # new width & height
img=ImageTk.PhotoImage(img)
e1 =tk.Label(picker)
e1.grid(row=15,column=1)
e1.image = img
e1['image']=img
def saveimage():
global filename
r=msgbox("save image?","image")
if r==True:
# encode image to binary text
with open(filename, "rb") as image:
# read the image as text and convert it to binary
image_string = base64.b64encode(image.read())
# create Gridfs instance
fs = gridfs.GridFS(mydb)
# add the image to database
def alreadyExists():
return bool(mycol2.find_one({'filename' : custid.get()}))
if alreadyExists() == True:
messagebox.showerror("Error", "ID exist")
else:
put_image = fs.put(image_string, filename = custid.get())
picker = tk.Frame(window,width=150, height=150)
picker.place(x=1, y=250)
b2 = tk.Button(window, text='Upload photo',
command = lambda:upload_file()).place(x=180, y=310)
b3 = tk.Button(window, text='Save photo',
command = lambda:saveimage()).place(x=180, y=340)
label =tk.Label(window, text="EMPLOYEE ENLISTMENT FORM", width=25, height=1, bg="cornflower blue",anchor="center")
label.grid(column=2, row=1)
label = tk.Label(window, text="Employee ID:", width=20, height=1, bg="cadet blue")
label.grid(column=1, row=2)
cid = tk.StringVar()
custid = tk.Entry(window,width=33, textvariable=cid)
custid.grid(column=2, row=2)
custid.configure(state=tk.DISABLED)
label = tk.Label(window, text="Employee Name:", width=20, height=1, bg="cadet blue")
label.grid(column=1, row=3)
cname = tk.StringVar()
custname = tk.Entry(window,width=33, textvariable=cname)
custname.grid(column=2, row=3)
age = []
for i in range(1960,2002):
age.append(i)
label=tk.Label(window, text="Employee BirthYear:", width=20, height=1, bg="cadet blue")
label.grid(row=4,column=1)
cage = tk.IntVar()
custage = ttk.Combobox(window,width=30, values=age)
custage.grid(row=4,column=2)
label=tk.Label(window, text="Employee Departure:", width=20, height=1, bg="cadet blue")
label.grid(row=5,column=1)
cdept = tk.StringVar()
dept=['Sale','Marketing']
custdept = ttk.Combobox(window,width=30, values=dept)
custdept.grid(row=5,column=2)
label=tk.Label(window, text="Employee Gender:", width=20, height=1, bg="cadet blue")
label.grid(row=6,column=1)
gender=['Male','Female']
cgender = tk.StringVar()
custgender = ttk.Combobox(window,width=30, values=gender)
custgender.grid(row=6,column=2)
label=tk.Label(window, text="Employee Skill:", width=20, height=1, bg="cadet blue")
label.grid(row=7,column=1)
cskill = tk.StringVar()
skill=['SQL, C#, Python','SQL, C#, C++','SQL, Python, C++','SQL, C++','SQL, Python','SQL, C#']
custskill = ttk.Combobox(window,width=30, values=skill)
custskill.grid(row=7,column=2)
label = tk.Label(window, text="Employee WorkingYear:", width=20, height=1, bg="cadet blue")
label.grid(column=1, row=8)
cwyear = tk.IntVar()
custwyear = tk.Entry(window,width=33, textvariable=cwyear)
custwyear.grid(column=2, row=8)
label = tk.Label(window, text="Employee Trained (Y):", width=20, height=1, bg="cadet blue")
label.grid(column=1, row=9)
ctyear = tk.IntVar()
custtyear = tk.Entry(window,width=33, textvariable=ctyear)
custtyear.grid(column=2, row=9)
label = tk.Label(window, text="Employee Salary:", width=20, height=1, bg="cadet blue")
label.grid(column=1, row=10)
csalary = tk.DoubleVar()
custsalary = tk.Entry(window,width=33, textvariable=csalary)
custsalary.grid(column=2, row=10)
creategrid(1) #create textfield grid vi o tren chay tu grid 1
savebtn = tk.Button(window,text="Save", command=save).place(x=180, y=275)
savebtn = tk.Button(window,text="Delete", command=delete).place(x=220, y=275)
savebtn = tk.Button(window,text="Update", command=update).place(x=270, y=275)
btnClose=tk.Button(window, text="Close me", command=window.destroy).place(x=180, y=370)
# Tim kiem anh dua tren ID
def searchImage():
window2=tk.Toplevel(w1)
window2.title("BROWSE")
window2.geometry('+%d+%d' % (100,100))
picker2 = tk.Frame(window2,width=30, height=1)
picker2.grid(row=1, column=3,rowspan = 10)
a = tk.Entry(picker2,width=33)
a.grid(column=2, row=11)
def checkid():
def alreadyExists():
return bool(mycol2.find_one({'filename' : a.get()}))
if alreadyExists() == True:
messagebox.showinfo("info", "ID exist")
fs = gridfs.GridFS(mydb)
data = mycol2.find_one({'filename' : a.get()})
my_id = data['_id']
outputdata =fs.get(my_id).read()
outputdata=outputdata.decode()
outputdata = base64.b64decode((outputdata))
dowloadlocation = "image.jpg"
output = open(dowloadlocation, "wb")
output.write(outputdata)
output.close()
bgetdisplay.config(state='active')
else:
messagebox.showerror("Error", "ID doesn't exist, please retype")
bgetdisplay.config(state='disabled')
def display():
root = Toplevel(window2)
path = "image.jpg"
img = Image.open(path)
img=img.resize((300,300))
img = ImageTk.PhotoImage(img)
panel = tk.Label(root, image=img)
panel.photo = img
panel.grid(column=1,row=1)
bgetdisplay = tk.Button(window2,state ='disabled', text='display image',
width=10,height=2,command = lambda:display())
bgetdisplay.grid(column = 5, row = 2)
bgetid = tk.Button(window2, text='checkID',
width=10,height=2,command = lambda:checkid()).grid(column = 4 ,row = 2)
label = tk.Label(picker2, text="browse photo(input id):", width=20, height=1, bg="cornflower blue")
label.grid(column=1, row=11)
w1=Tk()
btnOpen=tk.Button(w1,text ="Create, update, Delete",width=20,height=4, command=CRUD).place(x=120, y=20)
btnOpen=tk.Button(w1,text ="Search photo",width=20,height=4, command=searchImage).place(x=120, y=100)
w1.geometry('400x200')
w1.title("HUMAN RESOURES")
w1.mainloop()
I want to display data in a treeview to create a scrollbar.
Can anyone help to to change this display code

Need to validate the input of the name weight and height entries

https://github.com/Rodneyst/lv100roxas-gmail.com/blob/master/finalproject
Can look over the full code here. The link goes to the full code, I pull all the answer with one button using stringvar. Please answer I have 2 days left and haven't had any luck.
# Username widget
self.prompt_label5 = tkinter.Label(self.top_frame,
text='Enter your Name:' ,bg="red", fg="yellow", font="none 12 bold")
self.name_entry = tkinter.Entry(self.top_frame,
width=10)
# weight widget
self.prompt_label1 = tkinter.Label(self.top_frame,
text='Enter your weight(lbs):' ,bg="red", fg="yellow", font="none 12 bold")
self.weight_entry = tkinter.Entry(self.top_frame,
width=10)
def getworkout(self):
weight = float(self.weight_entry.get())
height = float(self.height_entry.get())
How would I validate these user inputs? Please help — I cannot figure it out. I want to get a pop-up window to show when the user inputs an integer for name and when they enter a string for weight and height, ValueErrors. Please help!
Code is messy, so make it look better :) But I think it does, what you asked about. I edited it in a hurry. Name also accept more signs then just letters (excluding integers) - it's easy to validate if necessery.
import tkinter
from tkinter import ttk
from tkinter import messagebox
import random
# GUI
class WorkoutGUI:
def __init__(self):
# Main window
self.main_window = tkinter.Tk()
self.main_window.title("Workout Generator")
self.main_window.geometry('1200x600')
# Frames
self.top_frame = tkinter.Frame()
self.mid_frame = tkinter.Frame()
self.bottom_frame = tkinter.Frame()
validation1 = self.top_frame.register(entry_validation_1)
validation2 = self.top_frame.register(entry_validation_2)
# TOP FRAME
# username widget
self.prompt_label1 = tkinter.Label(self.top_frame,
text='Enter your Name:', bg="red", fg="yellow", font="none 12 bold")
self.name_entry = tkinter.Entry(self.top_frame,
width=10, validate='key', validatecommand=(validation1, '%S'))
# weight widget
self.prompt_label2 = tkinter.Label(self.top_frame,
text='Enter your weight(lbs):', bg="red", fg="yellow", font="none 12 bold")
self.weight_entry = tkinter.Entry(self.top_frame,
width=10, validate='key', validatecommand=(validation2, '%S'))
# height widget
self.prompt_label3 = tkinter.Label(self.top_frame,
text='Enter your height(in):', bg="red", fg="yellow",
font="none 12 bold")
self.height_entry = tkinter.Entry(self.top_frame,
width=10, validate='key', validatecommand=(validation2, '%S'))
# gender widget
self.prompt_label4 = tkinter.Label(self.top_frame,
text='Select your gender:', bg="red", fg="yellow",
font="none 12 bold")
self.gender_entry = tkinter.IntVar()
self.gender_entry.set(1)
# radio buttons for gender choice
self.rb1 = tkinter.Radiobutton(self.top_frame,
text='Male',
variable=self.gender_entry,
value=1)
self.rb2 = tkinter.Radiobutton(self.top_frame,
text='Female',
variable=self.gender_entry,
value=2)
# goal widget
self.prompt_label5 = tkinter.Label(self.top_frame,
text='Select your goal:', bg="red", fg="yellow",
font="none 12 bold")
self.goal_entry = tkinter.IntVar()
self.goal_entry.set(1)
# radio buttons for goal choice
self.rb3 = tkinter.Radiobutton(self.top_frame,
text='Lose Weight',
variable=self.goal_entry,
value=1)
self.rb4 = tkinter.Radiobutton(self.top_frame,
text='Maintain',
variable=self.goal_entry,
value=2)
self.rb5 = tkinter.Radiobutton(self.top_frame,
text='Build Muscle Mass',
variable=self.goal_entry,
value=3)
# packing widgets
self.prompt_label1.pack(side='top')
self.name_entry.pack(side='top')
self.prompt_label2.pack(side='top')
self.weight_entry.pack(side='top')
self.prompt_label3.pack(side='top')
self.height_entry.pack(side='top')
self.prompt_label4.pack(side='top')
self.rb1.pack(side='top')
self.rb2.pack(side='top')
self.prompt_label5.pack(side='left')
self.rb3.pack(side='left')
self.rb4.pack(side='left')
self.rb5.pack(side='left')
# MIDDLE FRAME
self.descr_label = tkinter.Label(self.mid_frame,
text='Workout for you:')
self.value = tkinter.StringVar()
self.workout_label = tkinter.Label(self.mid_frame,
textvariable=self.value,
width=250, height=20, bg="white")
# packing widgets
self.descr_label.pack(side='top')
self.workout_label.pack(side='bottom')
# BOTTOM FRAME
# buttons
self.display_button = tkinter.Button(self.bottom_frame,
text='Get Workout!',
command=self.getworkout)
self.quit_button = tkinter.Button(self.bottom_frame,
text='Quit',
command=self.main_window.destroy)
# pack the buttons
self.display_button.pack(side='left')
self.quit_button.pack(side='right')
# packing frames
self.top_frame.pack()
self.mid_frame.pack()
self.bottom_frame.pack()
# fucnction to get outputs
def getworkout(self):
# Gather User information
name = str(self.name_entry.get())
gymSerial = random.randint(0, 10000)
weight = float(self.weight_entry.get())
height = float(self.height_entry.get())
gender = (self.gender_entry.get())
goal = (self.goal_entry.get())
def entry_validation_1(x):
if x.isdecimal():
messagebox.showwarning("Wrong input!", "Name must be a string - not integer.")
return False
else:
return True
def entry_validation_2(y):
if y.isdecimal():
return True
else:
messagebox.showwarning("Wrong input!", "Weight and height must be a numerical value - not string")
return False
def main():
root = tkinter.Tk()
ex = WorkoutGUI()
root.mainloop()
if __name__ == '__main__':
main()
Link is not working, but I wrote my own code as an example. I think it's very close to what you need.
The method is called entry validation and you can find some more info here:
https://anzeljg.github.io/rin2/book2/2405/docs/tkinter/entry-validation.html
Feel free to ask if you have any concerns :)
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
# tkinter main window
root = tk.Tk()
root.title('Validation')
root.geometry('300x300')
def entry_validation_1(x):
if x.isdecimal():
messagebox.showwarning("Wrong input!", "Name must be a string - not integer.")
return False
else:
return True
def entry_validation_2(y):
if y.isdecimal():
return True
else:
messagebox.showwarning("Wrong input!", "Weight and height must be a numerical value - not string")
return False
validation1 = root.register(entry_validation_1)
validation2 = root.register(entry_validation_2)
name = tk.Entry(root, width='9', justify='center', validate='key', validatecommand=(validation1, '%S'))
weight_or_height = tk.Entry(root, width='9', justify='center', validate='key', validatecommand=(validation2, '%S'))
label_name = tk.Label(root, text='name - INTEGER NOT ACCEPTED')
label_weight_or_height = tk.Label(root, text='weight or height - STRING NOT ACCEPTED')
name.grid(row=0, column=0, padx=0, pady=0)
label_name.grid(row=0, column=1, padx=0, pady=0)
weight_or_height.grid(row=1, column=0, padx=0, pady=0)
label_weight_or_height.grid(row=1, column=1, padx=0, pady=0)
tk.mainloop()

Tkinter Text widget returns ".!frame3.!frame3.!frame.!text" instead of appropriate values

I'm currently working on a project where you scan bar codes and it implements the result into an excel file. I am using tkinter to make my GUI, however, when I try to get the values from a text widget it returns the value ".!frame3.!frame3.!frame.!text". how can I fix this to get the appropriate values?
here is my code so far
import tkinter as tk
from tkinter import *
root = tk.Tk(className = "Tool Manager")
root.configure(bg='#C4C4C4')
root.title('Main Screen')
root.geometry("800x600")
main = Frame(root, bg='#C4C4C4', width = 800, height = 600)
#This is the contents of the Main Frame (screen 1)
frame_pad1 = Frame(main, bg='#C4C4C4')
frame_1 = Frame(main,bg='#C4C4C4')
frame_2 = Frame(main, bg='#C4C4C4')
frame_3 = Frame(main, bg='#C4C4C4')
min = Frame(root, bg = 'GREEN')
#mout stuffs
mout = Frame(root, bg = '#C4C4C4')
outframe_pad1 = Frame(mout, bg='#C4C4C4')
outframe_1 = Frame(mout, bg='#C4C4C4')
outframe_2 = Frame(mout, bg='#C4C4C4')
outframe_3 = Frame(mout, bg='#C4C4C4')
#code for changing screens
def raise_frame(frame):
frame.tkraise()
for frame in (main, min, mout):
frame.grid(row=1, column=1, sticky='news')
#sets frame weight for 3 rows (centers frames)
rows = 0
while rows < 3:
root.rowconfigure(rows, weight=1)
root.columnconfigure(rows,weight=1)
rows += 1
def commit_to_file():
ID = name.get()
out_list.get('1.0', 'end-1c')
print(out_list) #<----- THIS IS WHERE I'M RETURNING VALUES TO THE TERMINAL
def on_every_keyboard_input(event):
update_char_length(out_list)
#updating Line Length Information
def update_char_length(out_list):
string_in_text = out_list.get('1.0', '1.0 lineend')
string_length = len(string_in_text)
print(string_length)
if (string_length == 4):
out_list.insert(0.0, '\n')
out_list.mark_set("insert", "%d.%d" % (0,0))
#main screen formatting
area = PhotoImage(file="test.png")
areaLabel = Label(frame_1, image=area, bg='#C4C4C4')
areaLabel.pack(side=RIGHT)
mwLabel = Label(frame_2,text="this is only a test", font=("Airel", 20), bg='#C4C4C4')
mwLabel.pack(side=RIGHT)
out_button = Button(frame_3, text="Check Out", command=lambda:raise_frame(mout) , height=5, width=20, font=("Airel", 15))
out_button.pack(side=RIGHT, padx=20, pady = 4)
in_button = Button(frame_3, text="Check In", command=lambda:raise_frame(min), height=5, width=20, font=("Airel", 15))
in_button.pack(side=LEFT, padx=20, pady = 4)
#out screen formatting
name = Entry(outframe_1, font=("Airel", 15))
name.pack(side=RIGHT)
name_lbl = Label(outframe_1, text="ID Number", bg='#C4C4C4', font=("Airel", 15))
name_lbl.pack(side=LEFT)
outlist = Frame(outframe_2, bd=1, relief=SUNKEN)
outlist.pack(side=LEFT)
out_list = Text(outlist, height=30, width=40)
out_list.pack(side=RIGHT)
done_btn = Button(outframe_3, text="Done", command=commit_to_file, font=("Ariel", 15))
done_btn.pack(side=RIGHT, padx=20, pady=4)
#init to main screen
raise_frame(main)
#drawing objects for main screen
frame_pad1.pack(padx=1, pady=25)
frame_1.pack(padx=1,pady=1)
frame_2.pack(padx=10,pady=1)
frame_3.pack(padx=1, pady=80)
#drawing out screen
outframe_1.pack(padx=1, pady=1)
outframe_2.pack(padx=1,pady=1)
outframe_3.pack(padx=1, pady=1)
#calls line info update out screen
out_list.bind('<KeyRelease>', on_every_keyboard_input)
root.mainloop()
You are printing the command and not the value of it. Put the command in a variable and then print the variable.
Example: myVar = out_list.get("1.0", "end-1c") and then print(myVar)

How to specify the width of a frame when using grid in tkinker

I want to fix the width of my frame in this program.It is changing when clicking button.How can i set it to a default value.I did this program using tkinker .
import tkinter as tk
import math
class pythagores:
def __init__(self, master):
self.label = tk.Label(master, text="base")
self.label.grid(column=1, row=1)
self.base = tk.Entry(master, text="base")
self.base.grid(row=1, column=2)
self.label1 = tk.Label(master, text="altitude")
self.label1.grid(column=1, row=2)
self.altitude = tk.Entry(master, text="altitude")
self.altitude.grid(row=2, column=2)
self.button=tk.Button(master, text="Hypotenues", command=self.hypotenues)
self.button.grid(column=1, row=3)
self.label2 = tk.Label(master, text="")
self.label2.grid(row=4)
def hypotenues(self):
try:
alt = float(self.altitude.get())
bas = float(self.base.get())
hyp = math.sqrt((bas * bas) + (alt *alt))
self.label2['text'] = "Hypotenues is .."+str(hyp)
except:
self.label2['text'] = "Wrong Input"
return
root = tk.Tk()
pythagores(root)
root.mainloop()

Tkinter - How to display image when clicking a button?

First time here so forgive me as this is my FIRST attempt at making a silly GUI game (if you want to call it that). I'm trying to get the user to click a button and the image of their selection pops up. I can't seem to figure out how to get the image to pop up though.
Image does show if I run it separately.
My code:
from Tkinter import *
root = Tk()
class PokemonClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text="Welcome! Pick your Pokemon!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.CharButton = Button(root, text="Charmander", bg="RED", fg="White",
command=self.CharClick)
self.CharButton.pack(side=LEFT, fill=X)
self.SquirtButton = Button(root, text="Squirtle", bg="Blue", fg="White")
self.SquirtButton.pack(side=LEFT, fill=X)
self.BulbButton = Button(root, text="Bulbasaur", bg="Dark Green",
fg="White")
self.BulbButton.pack(side=LEFT, fill=X)
def CharClick(self):
print "You like Charmander!"
global CharSwitch
CharSwitch = 'Yes'
CharSwitch = 'No'
if CharSwitch == 'Yes':
CharPhoto = PhotoImage(file="Charmander.gif")
ChLabel = Label(root, image=CharPhoto)
ChLabel.pack()
k = PokemonClass(root)
root.mainloop()
This works, but the actual image no longer shows, if I keep the PhotoImage OUT of the class it will print but I want to have it print IF they click the specific button:
from Tkinter import *
root = Tk()
class PokemonClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text = "Welcome! Pick your Pokemon!", bg = "Black", fg = "White")
self.WelcomeLabel.pack(fill = X)
self.CharButton = Button(root, text = "Charmander", bg = "RED", fg = "White", command = CharClick)
self.CharButton.pack(side = LEFT, fill = X)
self.SquirtButton = Button(root, text = "Squirtle", bg = "Blue", fg = "White")
self.SquirtButton.pack(side = LEFT, fill = X)
self.BulbButton = Button(root, text = "Bulbasaur", bg = "Dark Green", fg = "White")
self.BulbButton.pack(side = LEFT, fill = X)
def CharClick():
print "You like Charmander!"
CharPhoto = PhotoImage(file = "Charmander.gif")
ChLabel = Label(root, image = CharPhoto)
ChLabel.pack()
k = PokemonClass(root)
root.mainloop()
You need to maintain a reference to your PhotoImage object. Unfortunately there is an inconsistency in tkinter in that attaching a Button to a parent widget increments the reference count, but adding an image to a widget does not increment the reference count. As a consequence at the moment the CharPhoto variable goes out of scope at the end of the function CharClick, the number of reference to the PhotoImage falls to zero and the object is made available for garbage collection.
If you keep a reference to the image somewhere, it will appear. When you kept it globally it remained in scope for the entire script and hence appeared.
You can keep a reference to it in the PokemonClass object or in the Label widget.
Below is the later of those options
from Tkinter import *
root = Tk()
class PokemonClass(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.WelcomeLabel = Label(root, text="Welcome! Pick your Pokemon!",
bg="Black", fg="White")
self.WelcomeLabel.pack(fill=X)
self.CharButton = Button(root, text="Charmander", bg="RED", fg="White",
command=self.CharClick)
self.CharButton.pack(side=LEFT, fill=X)
self.SquirtButton = Button(root, text="Squirtle", bg="Blue", fg="White")
self.SquirtButton.pack(side=LEFT, fill=X)
self.BulbButton = Button(root, text="Bulbasaur", bg="Dark Green",
fg="White")
self.BulbButton.pack(side=LEFT, fill=X)
def CharClick(self):
print "You like Charmander!"
global CharSwitch
CharSwitch = 'Yes'
CharPhoto = PhotoImage(file="Charmander.gif")
ChLabel = Label(root, image=CharPhoto)
ChLabel.img = CharPhoto
ChLabel.pack()
CharSwitch = 'No'
k = PokemonClass(root)
root.mainloop()
The solution which helped me is just simply declaring all the image variables on the next line after 'root = Tk()'. Doing so won't spoil your code or anything.

Categories

Resources