I have created a panedwindow in python tkinter with two panes. It will open fine on it's own but within an if statement it no longer opens
First I had just the code for the panedwindow on it's own but I wanted to use it within another section of code. It won't work within an if statement, it appears to be ignored. Where have I gone wrong?
from tkinter import *
import time
ticketCost=6
username="Rob"
code = input("Enter code: ")
if code == "123":
year=str(time.localtime()[0])
month=str(time.localtime()[1])
day=str(time.localtime()[2])
hour=str(time.localtime()[3])
minute=str(time.localtime()[4])
ticketTime=str(hour+":"+minute)
ticketDate=str(day+"/"+month+"/"+year)
ticketInfo="Bus ticket\nSingle\nDate: "+ticketDate+"\nTime: "+ticketTime+"\nPassengers: "+
...str(int(ticketCost/3))+"\nPrice: "+str(ticketCost)+" credits"
ticketWindow = PanedWindow(orient=VERTICAL,bg="white")
ticketWindow.pack(fill=BOTH, expand=1)
top = Label(ticketWindow, text="top pane")
photo = PhotoImage(file='Coach 1.gif')
top.config(image=photo,bg="white")
top.image = photo
ticketWindow.add(top)
bottom = Label(ticketWindow, text="bottom pane")
bottom.config(text=ticketInfo)
bottom.config(bg="white")
ticketWindow.add(bottom)
print("\nThank you", username)
else:
print("no")
You do not appear to be making a root window, and are not starting the event loop.
Related
I'm creating a counter to count how many empty cells there are when a user uploads a CSV file. I am also using treeview to display the contents of the CSV. The print("There are", emptyCells.sum(), "empty cells") works and prints the number to the console but I want to display this in a label so the user can view this in the GUI. It is not displaying anything but a "row" is being added to the application after a file has been uploaded where the label should be as everything moves down but no contents are being inserted into the label.
emptyCells = (df[df.columns] == " ").sum()
# print("There are", emptyCells.sum(), "empty cells")
tree.pack(side=BOTTOM, pady=50)
messagebox.showinfo("Success", "File Uploaded Successfully")
stringVariable = StringVar()
printVariable = ("There are", emptyCells.sum(), "empty cells")
#print(printVariable)
stringVariable.set(printVariable)
lbl = Label(windowFrame, textvariable=stringVariable, font=25)
lbl.pack()
According to your question you want to update your tkinter label by a button click. You would do this with something like this:
from tkinter import *
from tkinter import messagebox
root = Tk(className="button_click_label")
root.geometry("200x200")
messagebox.showinfo("Success","Test")
emptyCells = (df[df.columns] == " ").sum()
l1 = Label(root, text="Emptycells?")
def clickevent():
txt = "there are", emptyCells
l1.config(text=txt)
b1 = Button(root, text="clickhere", command=clickevent).pack()
l1.pack()
root.mainloop()
It is not tested with the pandas library but should work for you!
The problem with the tkinter label is not happening when I try to reproduce the problem, the label shows. The cause must be somewhere else in the code.
I've not got pandas installed so I've summed a list instead. This shows a GUI with two labels when I run it.
import tkinter as tk
emptyCells = [ 1, 1, 1, 1, 1, 1, 1 ] # keep it simple.
windowFrame = tk.Tk()
old = tk.StringVar()
stringVariable = tk.StringVar()
old_print = ("There are", sum(emptyCells), "empty cells") # Returns a tuple
printVariable = "There are {} empty cells".format( sum(emptyCells) ) # Returns a string.
old.set( old_print )
stringVariable.set(printVariable)
lbl_old = tk.Label( windowFrame, textvariable = old )
lbl_old.pack()
lbl = tk.Label(windowFrame, textvariable=stringVariable, font=25)
lbl.pack()
windowFrame.mainloop()
Does this work when you run it? Does it help identify where the problem is in the code which doesn't show the labels?
Don't you have the sum you need already in the emptyCells variable? Why do you need to use the .sum() function again in the print statement?
printVariable = f"There are {emptyCells} empty cells"
I'm trying to see if there's a way to type a number between 1 and 4 into an entry box, then go to the next entry box (with the number entered into the box; the code below skips to the next entry without entering anything)
I'm creating a program that will take item-level data entry to be computed into different subscales. I have that part working in different code, but would prefer not to have to hit tab in between each text entry box since there will be a lot of them.
Basic code:
from tkinter import *
master = Tk()
root_menu = Menu(master)
master.config(menu = root_menu)
def nextentrybox(event):
event.widget.tk_focusNext().focus()
return('break')
Label(master, text='Q1',font=("Arial",8)).grid(row=0,column=0,sticky=E)
Q1=Entry(master, textvariable=StringVar)
Q1.grid(row=0,column=1)
Q1.bind('1',nextentrybox)
Q1.bind('2',nextentrybox)
Q1.bind('3',nextentrybox)
Q1.bind('4',nextentrybox)
Label(master, text='Q2',font=("Arial",8)).grid(row=1,column=0,sticky=E)
Q2=Entry(master, textvariable=StringVar)
Q2.grid(row=1,column=1)
Q2.bind('1',nextentrybox)
Q2.bind('2',nextentrybox)
Q2.bind('3',nextentrybox)
Q2.bind('4',nextentrybox)
### etc for rest of questions
### Scale sums, t-score lookups, and report generator to go here
file_menu = Menu(root_menu)
root_menu.add_cascade(label = "File", menu = file_menu)
file_menu.add_separator()
file_menu.add_command(label = "Quit", command = master.destroy)
mainloop()
Thanks for any help or pointers!
The simplest solution is to enter the event keysym before proceeding to the next field.
In the following example, notice how I added a call to event.widget.insert before moving the focus:
def nextentrybox(event):
event.widget.insert("end", event.keysym)
event.widget.tk_focusNext().focus()
return('break')
I have had an issue with this piece of code from awhile back, it's part of a GCSE mock and I have currently finished the working code (with text only) but I would like to expand it so that it has a nice GUI. I'm getting some issues with updating my sentence variables within the code. Anyone with any suggestions for me please do explain how I can fix it.
#GCSE TASK WITH GUI
import tkinter
from tkinter import *
from tkinter import ttk
var_sentence = ("default")
window = tkinter.Tk()
window.resizable(width=FALSE, height=FALSE)
window.title("Sentence")
window.geometry("400x300")
window.wm_iconbitmap("applicationlogo.ico")
file = open("sentencedata.txt","w")
file = open("sentencedata.txt","r")
def update_sentence():
var_sentence = sentence.get()
def submit():
file.write(sentence)
print ("")
def findword():
messagebox.showinfo("Found!")
print ("Found")
sentencetext = tkinter.Label(window, fg="purple" ,text="Enter Sentence: ")
sentence = tkinter.Entry(window)
sentencebutton = tkinter.Button(text="Submit", fg="red" , command=update_sentence)
findword = tkinter.Label(window, fg="purple" ,text="Enter Word To Find: ")
wordtofind = tkinter.Entry(window)
findwordbutton = tkinter.Button(text="Find!", fg="red" ,command=findword)
usersentence = sentence.get()
usersentence = tkinter.Label(window,text=sentence)
shape = Canvas (bg="grey", cursor="arrow", width="400", height="8")
shape2 = Canvas (bg="grey", cursor="arrow", width="400", height="8")
#Packing & Ordering Moduales
sentencetext.pack()
sentence.pack()
sentencebutton.pack()
shape.pack()
findword.pack()
wordtofind.pack()
findwordbutton.pack()
usersentence.pack()
shape2.pack()
window.mainloop()
If I understand your question right, you want to display the entered text in the usersentence label.
Changing update_sentence() function to what is shown below will archive the desired effect.
def update_sentence():
var_sentence = sentence.get()
usersentence.config(text=var_sentence)
usersentence never gets updated because you only set it once when the program starts this was the problem.
I have written a program in Python that allow me to change the names of many files all at once. I have one issue that is quite odd.
When I use raw_input to get my desired extension, the GUI will not launch. I don't get any errors, but the window will never appear.
I tried using raw_input as a way of getting a file extension from the user to build the file list. This program will works correctly when raw_input is not used.The section of code that I am referring to is in my globList function. For some reason when raw_imput is used the window will not launch.
import os
import Tkinter
import glob
from Tkinter import *
def changeNames(dynamic_entry_list, filelist):
for index in range(len(dynamic_entry_list)):
if(dynamic_entry_list[index].get() != filelist[index]):
os.rename(filelist[index], dynamic_entry_list[index].get())
print "The files have been updated!"
def drawWindow(filelist):
dynamic_entry_list = []
my_row = 0
my_column = 0
for name in filelist:
my_column = 0
label = Tkinter.Label(window, text = name, justify = RIGHT)
label.grid(row = my_row, column = my_column)
my_column = 1
entry = Entry(window, width = 50)
dynamic_entry_list.append(entry)
entry.insert(0, name)
entry.grid(row = my_row, column = my_column)
my_row += 1
return dynamic_entry_list
def globList(filelist):
#ext = raw_input("Enter the file extension:")
ext = ""
desired = '*' + ext
for name in glob.glob(desired):
filelist.append(name)
filelist = []
globList(filelist)
window = Tkinter.Tk()
user_input = drawWindow(filelist)
button = Button(window, text = "Change File Names", command = (lambda e=user_input: changeNames(e, filelist)))
button.grid(row = len(filelist) + 1 , column = 1)
window.mainloop()
Is this a problem with raw_input?
What would be a good solution to the problem?
This is how tkinter is defined to work. It is single threaded, so while it's waiting for user input it's truly waiting. mainloop must be running so that the GUI can respond to events, including internal events such as requests to draw the window on the screen.
Generally speaking, you shouldn't be mixing a GUI with reading input from stdin. If you're creating a GUI, get the input from the user via an entry widget. Or, get the user input before creating the GUI.
A decent tutorial on popup dialogs can be found on the effbot site: http://effbot.org/tkinterbook/tkinter-dialog-windows.htm
So I'm writing a tKinter GUI for this project I'm working on, and I've run into a problem with one of my button methods. In the method for this button, the code prints a list of coordinates to a text file. It works great the first time, but if I press the button again before closing the root tKinter window, it doesn't truncate the file - it just adds the next set off coordinates to the end. Here is my code:
#print to file
reportFile = open('gridCenters.txt','w')
reportFile.write('In movement order:\n')
for x in xrange(0,len(coordinates)):
reportFile.write('%s\n' % str(coordinates[x]))
reportFile.close()
Now, this is within a button method, so to my understanding it should execute every time the button is pressed. The really strange part is that in the output after pressing the button again, it prints JUST the loop values. For some reason it skips over the "In movement order" part.
It won't let me upload images but here's an idea of how it looks:
In movement order:
(0,1)
(0,2.5)
(0.3.5)
(0,4.5)
Then if I press the button again before closing the root window:
In movement order:
(0,1)
(0,2.5)
(0.3.5)
(0,4.5)
(0,1)
(0,2.5)
(0.3.5)
(0,4.5)
(Those blocks aren't code, just text output)
I'm just really confused. My understanding is that every time I press the button, it should overwrite the file, then close it.
Thanks for the help.
In when your button re-opens the file it doesn't print the "In movement order:" a second time.
This looks like you aren't clearing your variable coordinates. You should make sure that you are starting with a clean variable before adding to it to get the data you are looking for.
You could reset it after the file closes unless you need to retain it for use un the GUI at that point.
I am not shure why it doesnt works for you but here is what i had wrote.
from Tkinter import *
def wtf(coordinates):
reportFile = open('gridCenters.txt','w')
reportFile.write('In movement order:\n')
for x in xrange(0,len(coordinates)):
reportFile.write('%s\n' % str(coordinates[x]))
reportFile.close()
def main():
coordinates = [(0,1),(0,2.5),(0,3.5),(0,4.5)]
root = Tk()
btn = Button(root,text='click me',command = lambda:wtf(coordinates))
btn.pack()
root.mainloop()
main()
in wtf function if 'w' is flag (reportFile = open('gridCenters.txt','w')) the gridCenters.txt is rewritten every time,but if the flag is 'a' instead of 'w' than result is just appending one below another.I hope this is what u want.
from Tkinter import *
coords = [1, 2, 3, 4, 5]
def write():
global coords
fileName = "testButton.txt"
fileObj = open(fileName, 'w')
fileObj.write("Some words\n")
for i in xrange(0, len(coords)):
fileObj.write("%d\n" %coords[i])
fileObj.close()
for i in range(5):
coords[i] += 1
root = Tk()
f = Frame(root).pack()
b = Button(root, text = "OK", command = write).pack(side = LEFT)
root.mainloop()
This works for me, overwriting the file every time and the values are updated every time as well. Something must be going on elsewhere in your program.