Here I am writing a code to give a different "mode" option to the user, after pressing the mode button my entry widget pops up and takes two values from the user for further work.
once the user presses the "enter" button my widget will be destroyed.
Here is my code ,it successfully takes values once from the user but when the user gives values 2nd time it shows error.
import tkinter as tk
import time
root=tk.Tk()
root.geometry("600x600")
root.title("User Interface Monitor")
rpm=tk.StringVar()
tim=tk.StringVar()
def enter():
global rpm,tim
root.rpmLabel=tk.Label(root,text="enter rpm value:")
root.rpmLabel.grid(row=0)
root.timeLabel=tk.Label(root,text="enter time in sec")
root.timeLabel.grid(row=1)
root.e1 = tk.Entry(root, textvariable=rpm)
root.e1.grid(row=0, column=1)
root.e1.delete(0,"end")
root.e2 = tk.Entry(root, textvariable=tim)
root.e2.grid(row=1, column=1)
root.e2.delete(0, "end")
#rpm=rpm.get()
#tim=tim.get()
#return rpm,tim
def gett():
global rpm, tim
rpm = rpm.get()
tim = tim.get()
print(rpm)
print(tim)
root.rpmLabel.destroy()
root.e1.destroy()
root.timeLabel.destroy()
root.e2.destroy()
#e1.pack()
#e2.pack()
root.Button1=tk.Button(root,text="MODE1",command=enter)
root.Button1.pack()
root.Button1.place(x=200,y=200)
root.Button2=tk.Button(root,text="Enter",command=gett)#root.Button2.pack()
root.Button2.place(x=260,y=200)
root.mainloop()
Here is my error
C:/Users/RAM/PycharmProjects/timing/rpm.py
23
2
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\RAM\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "C:/Users/RAM/PycharmProjects/timing/rpm.py", line 25, in gett
rpm = rpm.get()
AttributeError: 'str' object has no attribute 'get'
Process finished with exit code 0
I am new to Python, I couldn't find the solution for this error as tried with "delete" and "reset".
The problem is that rpm starts out as a StringVar and then you reset it to be a string in this line of code:
rpm = rpm.get()
Once that line of code runs, rpm is no longer a StringVar. A simple solution is to use a different name when fetching the value:
rpm_value = rpm.get()
Here, after carefully observing the error messages...
I changed my code line as Bryan suggested
rpm = rpm.get()
tim = tim.get()
to
rpm_value = rpm.get()
tim_value = tim.get()
then it works exactly as I want.
here is my output:
C:/Users/RAM/PycharmProjects/timing/rpm.py
rpm is : 740
time is : 12
want to test again?
enter values again
rpm is : 920
time is : 18
want to test again?
enter values again
Process finished with exit code 0
Related
I'm very new to Python and I'm trying to put my first application together that takes in trip information and inserts it into a text box for export out to a document. It's gone pretty good until today when I tried to implement multiple ways of inserting text from an entrybox into a text block with tkinter.
I have an entry widget that inserts text into a text widget when a button is pressed. That's simple enough but I wanted to make it to where you could simply hit the enter key to do the same thing.
When I implement this function I get the error:
"Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Spyder\pkgs\tkinter_init_.py", line 1892, in __ call __
return self.func(*args)
TypeError: insertstop() takes 0 positional arguments but 1 was given"
I've looked the error up and it seems like it would pop up if I put in arguments in my function call but I don't have any arguments in any of my function calls. Also it seems like maybe this error is related to a class or something? I haven't learned about classes yet and only have a basic idea of what they are. Do I need a class to do this?
Coincidentally I also added the argument(self) in my function and that made pressing enter work but it made my insert stop button quit working.
I'm sure I've missed something very basic but I just can't figure out what.
Thanks for any help!
import time
import os
import sys
from tkinter import *
# Creates the Tkinter form named "screen"
screen = Tk()
screen.geometry("550x645")
screen.title("Test")
# Initialize frames
menuframe = Frame(screen,
height=60,width=600,bg="gray",pady=5)
inputframe = Frame(screen,
height=300,width=600,pady=5)
outputframe = Frame(screen,
height=290,width=600,pady=5)
# Packs the frames so they will display
menuframe.pack()
inputframe.pack()
outputframe.pack()
#==STOPBOX==#
stopbox=Text(inputframe,yscrollcommand=1,height= 10,width=20,
padx=3,pady=3,relief=GROOVE,bg="gray79")
stopbox.place(x=345, y=90)
def insertstop():
global stop_vanconv
stop_vanconv=(stop_entry.get())
stopbox.insert(END, stop_vanconv + "\n")
stop_entry.delete("0","end")
stoplist_label = Label(inputframe,
text="Type stop locations and press" + '\n' +
"the Add Stop button to insert a new stop.")
stoplist_label.place(x=100, y=150)
stop_entry = Entry(inputframe,
textvariable = " ")
stop_entry.place(x=150, y=190)
addstopbutton = Button(inputframe,text="Add Stop",padx=20,pady=0,
activebackground="darkslategray4",command=insertstop)
addstopbutton.place(x=160, y=220)
stop_entry.bind('<Return>',insertstop)
screen.mainloop()
I accidentally created an infinite loop :DWith the function below I want to call a warning (if a file does not exist) when the user operates the tkinter Scale. This message should be displayed only once. But when the user clicks (in the middle) on the tkinter Scale button, the Scale button is dragged to the end and the message is called again and again.
How can I prevent this?
def change_max_y(v):
try:
# Some functions to check if the file exists
# Open some json file
# Do some calculation
except FileNotFoundError:
# Some function to open the messagebox:
comment = tk.messagebox.askyesno('Title', "Something is missing.", icon='warning')
if comment:
# Do something
else:
return
ttk.Scale(settingsWin, orient=tk.HORIZONTAL, from_=0, to=4, length=110, command=change_max_y). \
place(x=210, y=90)
You can define a global variable (i know it's bad practice, but sometimes it must be done) with a initial value of 0. In your callback function, you look if that variable is 0, if yes, you show your message box and set it to 1. If no, you do nothing. The code you provided modified accordingly :
already_shown = 0
def change_max_y(v):
try:
# Some functions to check if the file exists
# Open some json file
# Do some calculation
except FileNotFoundError:
# Some function to open the messagebox:
if not already_shown:
comment = tk.messagebox.askyesno('Title', "Something is missing.", icon='warning')
already_shown = 1
if comment:
# Do something
else:
return # note : you can delete this else statement, as the function
# will return None by itself when there is nothing more to be
# done
ttk.Scale(settingsWin, orient=tk.HORIZONTAL, from_=0, to=4, length=110, command=change_max_y). \
place(x=210, y=90)
im getting the above error when i run this code snippet. Im trying to error proof user input by creating an error window when the user enters a value not in a dataframe. the code im running is below
import tkinter as tk
import tkinter.messagebox
import pandas as pd
root= tk.TK()
def customer_search():
try:
search = int(entry1.get())
except ValueError:
tk.messagebox("that customer doesnt exist, please enter a new number") #error proofing has to be added tomorrow
search = int(entry1.get())
k = df.loc[df['UniqueID'] == search]
k.to_excel("dashboard.xlsx")
df.to_excel("check.xlsx")
canvas1 = tk.Canvas(root, width=400, height=300)
canvas1.pack()
entry1 = tk.Entry(root)
canvas1.create_window(200, 140, window=entry1)
button1 = tk.Button(text='Enter a customer for analysis', command=customer_search)
button1.pack()
the error i get is as follows
Exception in Tkinter callback
Traceback (most recent call last):
File "C:/Users/....py", line 42, in customer_search
search = int(entry1.get())
ValueError: invalid literal for int() with base 10: 'a'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users...\__init__.py", line 1705, in __call__
return self.func(*args)
File "C:/Users....py", line 44, in customer_search
tk.messagebox("that customer doesnt exist, please enter a new number") #error proofing has to be added tomorrow
TypeError: 'module' object is not callable
Process finished with exit code 0
tk.messagebox is a module containing multiple dialogs, you probably want to use tk.messagebox.showerror("Info Title", "Info content").
Other dialogs are showwarning and showinfo, depending on your use case.
tk.messagebox is a module not a function. A basic difference between modules and functions is that:
You can't call modules, i.e., you can't do module(). (This is precisely the mistake you are making.)
You can call functions, i.e., you can do function(). (This is what you should be doing instead.)
You need to do it this way (in customer_search):
tk.messagebox.showerror("Title here", "that customer doesnt exist, please enter a new number")
where tk.messagebox.showerror is a function in tk.messagebox module.
I am working on a project that will eventually simulate a filter for Twitter posts. I am trying to make a page in Tkinter that will allow the user to enter a Twitter account, and press a button that will add the string to a list and clear the entry field (have yet to code the append function). Code is as follows:
def Add():
F.title('Twitter Filter: Add to Filter')
def h_delete():
Entry.delete(h,first=0,last=END) # should clear entry, instead returns NoneType error
for widget in F.winfo_children():
widget.destroy() # clears widgets of previous window
global a1
a1=tk.StringVar() # declares a variable that will be used to append a list with the text in the Entry
h=tk.Entry(F,textvariable=a1).grid(row=1,column=1) # creates the entry I want cleared
EntryButton=tk.Button(F,text='Add this account',command=h_delete).grid(row=2,column=1) # initiates the entry clearing function
BackButton=tk.Button(F,text='Back to Home',command=Home).grid(row=3,column=1) # returns to home screen
However, when I run the code, I receive a NoneType error, as follows:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 1550, in __call__
return self.func(*args)
File "/Users/skor8427/Desktop/Twitter Filter/TwitterFilter.py", line 22, in h_delete
Entry.delete(h,first=0,last=END) # should clear entry, instead returns NoneType error
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 2519, in delete
self.tk.call(self._w, 'delete', first, last)
AttributeError: 'NoneType' object has no attribute 'tk'
I have read various help sections and nothing is working. Anyone have a solution?
h = tk.Entry(F, textvariable=a1)
h.grid(row=1, column=1)
You have to grid h in other line else it will become NoneType
Try this snippet of code instead of
h = tk.Entry(F, textvariable=a1).grid(row=1, column=1)
Good evening,
I'm trying to learn some Python coding so I've written a short script that searches the screen for a button and then clicks the button a specified number of times. I have the code under 'RunScript' also saved as it's own file. When I run that script from terminal it works fine, but when I try to execute it by double clicking the icon, or from a button on a tkinter box using the below code it asks me for a number of loops and then does nothing. I'm working in a Lubuntu virtual machine.
Please can you tell me what I'm missing?
Thank you
#!/usr/bin/python3
from tkinter import *
import pyautogui
import easygui
PauseStatus = False
def RunScript():
LoopCount = easygui.enterbox('How Many Loops?')
for i in range (int(LoopCount)):
if PauseStatus:
easygui.msgbox(str(i) + ' loops completed\n' + str(int(LoopCount)-i) + 'loops remaining')
PauseStatus = False
while True:
ButtonPos = pyautogui.locateOnScreen('MyButton.png')
if ButtonPos is not None:
break
pyautogui.click(ButtonPos[0],ButtonPos[1],duration=0.25)
while True:
ButtonPos = pyautogui.locateOnScreen('MyButton.png')
if ButtonPos is not None:
break
easygui.msgbox(str(i+1) + ' loops completed')
root = Tk()
ControlPanel = Frame(root)
ControlPanel.pack()
startbutton = Button(ControlPanel, text="Start",command = RunScript)
startbutton.pack(side = LEFT)
stopbutton=Button(ControlPanel,text="Stop")
stopbutton.pack(side = LEFT)
root.mainloop()
You have error message similar to this
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1539, in __call__
return self.func(*args)
File "<pyshell#3>", line 11, in RunScript
if PauseStatus:
UnboundLocalError: local variable 'PauseStatus' referenced before assignment
You have to use global in function RunScript
def RunScript():
global PauseStatus
or you have to declare variable inside function as local variable
def RunScript():
PauseStatus = False