i want to create a area of circle calculator because i have some free time so i tried to run it first in to the terminal and it works but when i decide to add a litte GUI well i got an error
My code is this
from tkinter import *
screen = Tk()
screen.title("Area of Circle Calculator")
screen.geometry("500x500")
def submit():
global done
pi = 3.14159265359
an = int(pi * radius*radius)
laod = Label(screen, text = "Hello" % (an))
load.grid()
ask = Label(screen, text = "What is the radius of the circle?")
ask.pack()
radius = Entry(screen)
radius.pack()
done = Button(screen, text="submit", command = submit)
done.pack()
screen.mainloop()
and this is the error that i got
C:\Users\Timothy\Desktop>python aoc.py
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Timothy\AppData\Local\Programs\Python\Python37-32\lib\tkinter\_
_init__.py", line 1705, in __call__
return self.func(*args)
File "aoc.py", line 8, in submit
an = int(pi * radius*radius)
TypeError: unsupported operand type(s) for *: 'float' and 'Entry'
C:\Users\Timothy\Desktop>
i try to add int() in to the entry but it dosent work
You need to call radius.get() to get the Entry widget's current value.
Here's some documentation on it.
There were some other errors and a typo in your code, so I fixed them and made it more PEP 8 - Style Guide for Python Code compliant.
Here's the result:
from math import pi
from tkinter import *
screen = Tk()
screen.title("Area of Circle Calculator")
screen.geometry("500x500")
def submit():
r = float(radius.get())
an = pi * r**2
load = Label(screen, text="Hello %f" % (an))
load.pack()
ask = Label(screen, text="What is the radius of the circle?")
ask.pack()
radius = Entry(screen)
radius.pack()
done = Button(screen, text="submit", command=submit)
done.pack()
screen.mainloop()
Related
I'm trying to make a more user friendly screen crosshair for games like Apex Legends,because exsisted ones can't atuomaticlly go disappear when you returns to desktop,minimize the game window or switch to a browers while the game is still running with borderless window mode.I chose Python to make it because I'm most familiar with it(just started to learn coding recently).You can see my codes and error information below:
import time
from tkinter import *
class CrosshairWindow:
def __init__(self):
self.root = Toplevel()
self.root.attributes(
'-transparentcolor', '#ffffff',
'-topmost', '1'
)
self.root.overrideredirect(1)
self.screen_width = self.root.winfo_screenwidth()
self.screen_height = self.root.winfo_screenheight()
def start(self):
image = PhotoImage(file='crosshair.png')
canvas = Canvas(self.root, width=image.width(), height=image.height(), highlightthickness=0)
canvas.pack(fill='both')
canvas.create_image(0, 0, anchor=NW, image=image)
self.root.geometry(f'%sx%s+%s+%s' % (
image.width(), # width
image.height(), # height
round(self.screen_width/2 - image.width()/2), # x offset
round(self.screen_height/2 - image.height()/2), # y offset
))
self.root.lift()
self.root.mainloop()
if __name__ == '__main__':
import win32gui as w
print('Started!')
while(True):
title = w.GetWindowText(w.GetForegroundWindow())
print(title)
cw = CrosshairWindow()
while 1:
time.sleep(1)
print(title)
title = w.GetWindowText(w.GetForegroundWindow())
if title == "Apex Legends":
key = True
else:
key = False
print(title)
if key==True:
cw.start()
else:
cw.root.destroy()
C:\ProgramData\Anaconda3\python.exe "C:/Users/Hosisora_Ling/Documents/Tencent Files/2374416274/FileRecv/crosshair.py"
Started!
新建文件夹 – C:\Users\Hosisora_Ling\Documents\Tencent Files\2374416274\FileRecv\crosshair.py
Traceback (most recent call last):
File "C:\Users\Hosisora_Ling\Documents\Tencent Files\2374416274\FileRecv\crosshair.py", line 41, in <module>
cw.start(0)
File "C:\Users\Hosisora_Ling\Documents\Tencent Files\2374416274\FileRecv\crosshair.py", line 33, in start
self.root.lift()
File "C:\ProgramData\Anaconda3\lib\tkinter\__init__.py", line 1026, in tkraise
self.tk.call('raise', self._w, aboveThis)
_tkinter.TclError: can't invoke "raise" command: application has been destroyed
进程已结束,退出代码1#program ended with exit code 1
Please help point out the mistakes or a posible way to achieve my goal!
I am creating soft with Tkinter. I am trying to set an icon using root.iconbitmap('Globe.ico'). it works fine when I launch code. But after I compile it with pyinstaller it crashes. when i remove root.iconbitmap('Globe.ico') function and compile it works fine. bellow is error and the code :
Traceback (most recent call last):
File "word.py", line 294, in <module>
File "tkinter\__init__.py", line 1871, in wm_iconbitmap
_tkinter.TclError: bitmap "Global.ico" not defined
[5128] Failed to execute script word
from tkinter import filedialog, messagebox
from tkinter import *
from tkinter.ttk import *
root = Tk()
root.title("some title")
#line bellow crashes app
root.iconbitmap('Global.ico')
progress=Progressbar(root,orient=HORIZONTAL,length=500,mode='indeterminate')
progress.grid(row=3,column=1)
l2 = Label(root, text="File Name").grid(row=0,column =0)
e1_value =StringVar()
e1=Entry(root,textvariable=e1_value,width=80)
e1.grid(row=0,column=1)
b1 = Button(root, text = "Select Folder",command = directory )
b1.grid(row=1,column =0)
b2 = Button(root, text = "Execute",command = run_transformations )
b2.grid(row=4,column=1)
t1 = Text(root,height=1,width=60)
t1.grid(row=1,column =1 )
t1.configure(state='disabled')
v = IntVar()
r1 = Radiobutton(root,text='Rows as Columns',variable=v , value = 1).grid(row=2,column=0,columnspan =2,ipadx = 100)
r2 = Radiobutton(root,text='Columns as Columns',variable=v , value = 2).grid(row=2,column=1 ,columnspan =3,ipadx = 0)
v.set(1)
buttons = [ b1,b2]
root.mainloop()
I had same problem. Full path would solve this issue.
ex) root.iconbitmap('d:\test\Global.ico')
I have a very basic question, i.e. by using Python Tkinter window I want to show list box and from that list, I want to show some information which I select. But I am getting some error.
import Tkinter
from Tkinter import*
import tkMessageBox
window = Tk()
window.title('ex - 4,listing option')
frame = Frame(window)
listbox = Listbox(frame)
listbox.insert(1, 'Manual')
listbox.insert(2, 'Auto')
listbox.insert(3, 'AI')
def dialog():
tkMessageBox('selection','your chice:' + \
listbox.get(listbox.curselection()))
btn = Button(frame, text = 'Choose',command = dialog)
btn.pack(side = RIGHT, padx = 5)
listbox.pack(side = LEFT)
frame.pack(padx = 30, pady = 30)
window.mainloop()
The error is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1410, in __call__
return self.func(*args)
File "C:\Users\Subhro Jyoti\Desktop\python\ex - 4,listing option", line 12, in dialog
tkMessageBox('selection','your chice:' + listbox.get(listbox.curselection()))
TypeError: 'module' object is not callable
tkMessageBox is a collection of different types of message boxes, you have to indicate which one you want to use. For example:
def dialog():
tkMessageBox.showinfo('selection','your chice:' +
listbox.get(listbox.curselection()))
Your choices are showinfo, showwarning, showerror, askquestion, askokcancel, askyesno, or askretrycancel
The goal of this program is to generate a sine wave using a 12 bit DAC. The code is as follows:
from Tkinter import *
import smbus, time, math, random
bus = smbus.SMBus(1)
address = 0x60
t=time.time()
class RPiRFSigGen:
# Build Graphical User Interface
def __init__(self, master):
self.start
frame = Frame(master, bd=10)
frame.pack(fill=BOTH,expand=1)
# set output frequency
frequencylabel = Label(frame, text='Frequency (Hz)', pady=10)
frequencylabel.grid(row=0, column=0)
self.frequency = StringVar()
frequencyentry = Entry(frame, textvariable=self.frequency, width=10)
frequencyentry.grid(row=0, column=1)
# Start button
startbutton = Button(frame, text='Enter', command=self.start)
startbutton.grid(row=1, column=0)
def start(self):
#self.low_freq=IntVar
low_freq = float(self.frequency.get())
out = 4095/2 + (math.sin(2*math.pi*low_freq*t))
#out = math.floor(out)
int(math.floor(out))
print (out)
bus.write_byte_data(address,0,out)
sendFrequency(low_freq)
# Assign TK to root
root = Tk()
# Set main window title
root.wm_title('DAC Controller')
root.geometry('250x150+650+250')
# Create instance of class RPiRFSigGen
app = RPiRFSigGen(root)
# Start main loop and wait for input from GUI
root.mainloop()
When I run the program I receive the following error after the value "out" is printed:
2046.18787764
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1437, in __call__
return self.func(*args)
File "/home/pi/DAC Controller.py", line 40, in start
bus.write_byte_data(address,0,out)
TypeError: integer argument expected, got float
It would appear that int(math.floor(out)) is not converting out to an integer because "out" is being printed as float still. Any suggestions?
int(math.floor(out))
This will create an integer version of out, but you aren't assigning it to anything, so it just gets discarded. If you want the changes to be reflected in the value of out, try:
out = int(math.floor(out))
This is my code :
import sys
from tkinter import *
#first new screen
def hypoténusegetdef ():
widgets1 = button1
nextscreen1(widgets1)
def next_screen1(names):
for widget in names:
widget.place_forget()
hyplabel1 = Label (text = "This is my text")
def next_screen(names):
for widget in names:
widget.place_forget()
button1 = Button (text = "Button1",fg = "blue",command = hypoténusegetdef)
button1.grid (row = 1,column = 2)
def forget_page1():
widgets = [mLabel1, button]
next_screen(widgets)
################################################################################
#first page things
mGui = Tk ()
mGui.geometry("600x600+545+170")
mGui.title("MyMathDictionary")
mLabel1 = Label (text = "Welcome to MyMathDictionary. Press Next to continue.",
fg = "blue",bg = "white")
mLabel1.place (x= 150,y = 200)
button = Button (text = "Next", command = forget_page1 )
button.place(x = 275,y = 230)
mGui.mainloop()
I want the user to click on "next" and then a button appears caled "button1" after clicking on that button a text should appear "this is my text" but it gives me an error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python33\lib\tkinter\__init__.py", line 1475, in __call__
return self.func(*args)
File "C:\Python33\Projects\MyMathDictionary.py", line 7, in hypoténusegetdef
widgets1 = button1
NameError: global name 'button1' is not defined
Any help would be apreciated :
button1 is defined in next_screen, but used in hypoténusegetdef -- you can't use a variable from one function inside another. Looking at the rest of the code, the simplest thing would probably be to use a global variable that can be accessed anywhere (generally bad practice, but for short scripts they can make things easier)