How to connect the Calculator GUI to the graph GUI? - python

I want to connect calculator gui with function graph gui.
For example
if I clicked 'sinx' on the calculator, the graph(which is sine function) would be apear on graph gui.
How could I do?
Calculator GUI code
from tkinter import *
window = Tk()
window.title("해대비주얼")
''
top_row = Frame(window)
top_row.grid(row=0, column=0, columnspan=2, sticky=N)
display = Entry(top_row, width=35, bg="light blue")
display.grid()
num_pad = Frame(window)
num_pad.grid(row=1, column=0, sticky=W)
num_pad_list = [
'7','8','9',
'4','5','6',
'1','2','3',
'0','.','=']
r = 0
c = 0
for btn_text in num_pad_list:
def cmd(x=btn_text):
click(x)
Button(num_pad, text=btn_text, width=5, command=cmd).grid(row=r, column=c)
c = c + 1
if c > 2:
c = 0
r = r + 1
operator = Frame(window)
operator.grid(row=1, column=1, sticky=E)
operator_list = [
'*','/',
'+','-',
'(',')',
'^','C']
r = 0
c = 0
for btn_text in operator_list:
def cmd(x=btn_text):
click(x)
Button(operator, text=btn_text, width=5, command=cmd).grid(row=r, column=c)
c = c + 1
if c > 1:
c = 0
r = r + 1
etc = Frame(window)
etc.grid(row=50, column=0, sticky=S)
etc_list = ['pi','sin','cos','x']
r = 0
c = 0
for btn_text in etc_list:
def cmd(x=btn_text):
click(x)
Button(etc, text=btn_text, width=5, command=cmd).grid(row=r, column=c)
r = 0
c = c + 1
def click(key):
if key == "=":
try:
if "^" in display.get():
n = display.get().split(sep="^")
result = str(float(n[0]) ** float(n[1]))
display.insert(END, " = " + result)
else:
result = str(eval(display.get()))[0:10]
display.insert(END, " = " + result)
except:
display.insert(END, " --> Error!")
elif key == "C":
display.delete(0, END)
elif key == etc_list[0]:
import math
display.insert(END, math.pi)
else:
display.insert(END, key)
window.mainloop()
2.Graph GUI code
from tkinter import *
graph = Tk()
graph.title("해대비주얼 그래프")
''
graph.geometry("1000x700")
''

Related

TypeError: knapSack() missing 3 required positional arguments

I just start learning tkinter python for knapsack program. When I try to calculate, it doesn't do anything. And I am getting this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/tkinter/init.py", line 1921, in call
return self.func(*args)
TypeError: knapSack() missing 3 required positional arguments: 'W', 'wt', and 'val'
My code looks like this
import tkinter as tk
window = tk.Tk()
window.title("0/1 Knapsack")
canvas = tk.Canvas(window, height=1000, width=1000, bg = "#ADD8E6")
canvas.pack()
frame = tk.Frame(window, bg="white")
frame.place(relwidth=0.8, relheight=0.8,relx=0.1,rely=0.1)
def on_submit():
num_entries = int(num_entries_entry.get())
for i in range(num_entries):
Title_label = tk.Label(frame, text = "Items information")
Title_label.grid(row=5, column=1)
Title_label.config(font=("Arial", 18))
entry = tk.Entry(frame)
entry_label = tk.Label(frame, text = " Weight of items : " )
entry_label.grid(row=6,column=0)
entry.grid(row=7+i, column=0)
entry2 = tk.Entry(frame)
entry2_label = tk.Label(frame, text = " Value of each items")
entry2_label.grid(row=6, column=1)
entry2.grid(row=7+i, column=1)
capacity_label = tk.Label(frame, text =" Please select the capacity of your bag :")
capacity_spinbox = tk.Spinbox(frame, from_=1, to=100 )
capacity_label.grid(row=6, column=2)
capacity_spinbox.grid(row=7,column=2)
calculate_button =tk.Button(frame,text="Calculate", command = knapSack)
calculate_button.grid(row=7,column=3)
def calculate(weights, values, capacity):
result = knapSack(capacity, weights, values)
# Create a label to display the result
result_label = tk.Label(frame, text="Result: " + str(result))
result_label.grid(row=14, column=0)
def print_value_table(table):
print("Value Table:")
for row in table:
print(row)
def print_keep_table(table):
print("Keep Table:")
for row in table:
print(row)
def knapSack(W, wt, val):
n=len(val)
value_table = [[0 for x in range(W + 1)] for x in range(n + 1)]
keep_table = [[0 for x in range (W+1)] for x in range (n+1)]
for i in range(n + 1):
for j in range(W + 1):
if i == 0 or j == 0:
value_table[i][j] = 0
keep_table[i][j] = 0
elif wt[i-1] <= j:
if(val[i-1] + value_table[i-1][j-wt[i-1]]) > value_table[i-1][j]:
value_table[i][j] = val [i-1]+ value_table[i-1][j-wt[i-1]]
keep_table [i][j] = 1
else:
value_table[i][j] = value_table[i-1][j]
keep_table[i][j] = 0
else:
value_table[i][j] = value_table[i-1][j]
keep_table[i][j] = 0
print_value_table(value_table)
print_keep_table(keep_table)
return value_table[n][W]
num_entries_label = tk.Label(frame, text="Enter the number of items:")
num_entries_label.grid(row=1, column=1)
num_entries_entry = tk.Entry(frame)
num_entries_entry.grid(row=2, column=1)
next_button = tk.Button(frame, text="Next", command=on_submit)
next_button.grid(row=3, column=1)
title_label = tk.Label(frame, text = "Hi! Please follow the instructions!")
title_label.config(font=("Arial", 18))
window.mainloop()

unit testing a tkinter application

Someone can suggest how you can make simple tests here.
This is a simple keyboard trainer on tkinter, a window appears where you can select the difficulty level and start the game.
Or if you can give a link to a resource with explanations
from tkinter import *
import sys
import time
from random import choices
root = Tk() # Создаем основное окно
top = Toplevel() # Создаем окно для выбора сложности
# добавляем виджеты в окно выбора сложности
var = IntVar()
Radiobutton(top, text='Легкая', variable=var, value=0).pack()
Radiobutton(top, text='Нормальная', variable=var, value=1).pack()
Radiobutton(top, text='Сложная', variable=var, value=2).pack()
button1 = Button(top, text="Играть", command=lambda: command()).pack()
button2 = Button(top, text="Выйти", command=lambda: command2()).pack()
def command():
global test_words1
if var.get() == 0:
with open("words.txt", "r") as words:
test_words1 = choices(list(words), k=1)
dif()
elif var.get() == 1:
with open("words.txt", "r") as words:
test_words1 = choices(list(words), k=2)
dif()
elif var.get() == 2:
with open("words.txt", "r") as words:
test_words1 = choices(list(words), k=3)
dif()
pos = 0
b = 0
mistakes = 0
correct_presses = 0
def key_type(e):
if e.keycode != 16:
global pos, text_widget, b, mistakes, correct_presses
if (test_text[pos] != e.char):
text_widget.tag_add("wrong", str(1) + "." + str(b))
mistakes += 1
if (test_text[pos] == e.char):
text_widget.tag_add("correct", str(1) + "." + str(b))
correct_presses += 1
b += 1
pos += 1
if (pos == len(test_text)):
end_time = time.time()
rav=end_time-start_time
label1 = Label(root2,text="NICE!", fg="#eee", bg="#957")
label1.pack()
label2 = Label(root2, text="TIME:", fg="#eee", bg="#957")
label2.pack()
label0 = Label(root2,text=rav, fg="#eee", bg="#957")
label0.pack()
def dif():
root.withdraw()
top.destroy() # Уничтожаем окно выбора сложност
global root2
root2 = Tk() # Создаем основное окно
root2.deiconify() # Показываем основное окно
top.destroy() # Уничтожаем окно выбора сложности
global start_time
start_time = time.time()
global test_text
global text_widget
len_word_list = [len(word.strip()) for word in test_words1]
index_nostrip1 = 6
end_of_line1 = 0
final_word_list1 = []
lines_list1 = []
line1 = ""
for i in range(len(test_words1)):
if end_of_line1 == index_nostrip1 - 1:
final_word_list1.append(test_words1[i])
line1 += test_words1[i].strip()
lines_list1.append(line1)
line1 = ""
end_of_line1 = 0
else:
final_word_list1.append(test_words1[i].strip())
line1 += f"{test_words1[i].strip()} "
end_of_line1 += 1
# create the final string to be used in the test
test_text = " ".join(final_word_list1)
text_widget = Text(root2, height=10, width=100,
padx=20, pady=20, font=("Arial ", 16))
text_widget.insert(END, test_text)
text_widget.configure(state="disabled")
text_widget.tag_config("correct", background="green", foreground="white")
text_widget.tag_config("wrong", background="red", foreground="white")
text_widget.bind("<KeyPress>", key_type)
text_widget.focus()
text_widget.pack()
message = Label(root,
text="Start typing",
font=("Arial ", 24))
message.pack()
root2.mainloop()
# эта команда выполняется по кнопке Выйти
def command2():
top.destroy() # Уничтожаем окно выбора сложности
root.destroy() # Уничтожаем основное окно
sys.exit() # Выходим из программы
root.withdraw() # Скрываем основное окно, пока показываем окно выбора сложности
root.mainloop()
I have already tried to write something similar, but the tests do not pass
class TKinterTestCase(unittest.TestCase):
def setUp(self):
self.root=tkinter.Tk()
self.pump_events()
def tearDown(self):
if self.root:
self.root.destroy()
self.pump_events()
def pump_events(self):
while self.root.mainloop(_tkinter.ALL_EVENTS | _tkinter.DONT_WAIT):
pass
if __name__ == '__main__':
unittest.main()

tkinter: pull down menu un-clickable

I am creating a tkinter window that updates a matrix multiplication result every second. I wish to use pull down menus to create options for users.
However, since the entire window is re-drawn every second for the matrix update, the pull down menus are re-initialized every second, rendering them pretty much useless.
I am wondering if there is any way around this problem.
Thanks in advance.
from tkinter import *
import time
import sys
def update(a):
root.title("Matrix Multiplication")
menu = Menu(root)
root.config(menu= menu)
subMenu = Menu(menu)
menu.add_cascade(label="Options", menu=subMenu)
subMenu.add_command(label="Opt1...",command=win2)
exitMenu = Menu(menu)
menu.add_cascade(label="Exit", menu=exitMenu)
exitMenu.add_command(label="Exit",command=root.destroy)
X0 = [[8,7,3],[4 ,5,6],[7 ,8,9]]
Y0 = [[5,8,1,2],[6,7,3,0],[4,5,9,1]]
result0 = [[0,0,0,0],[0,0,0,0],[0,0,0,0]]
if a == 0:
cpfg = ["magenta", "blue", "green", "purple"]
cpbg = ["white", "white", "white", "white"]
button1 = Button(root, text="Button-1", fg=cpfg[0], bg=cpbg[0])
button2 = Button(root, text="Button-2", fg=cpfg[1], bg=cpbg[1])
button3 = Button(root, text="Button-3", fg=cpfg[2], bg=cpbg[2])
button4 = Button(root, text="Button-4", fg=cpfg[3], bg=cpbg[3])
button1.grid(row=0, column=0)
button2.grid(row=0, column=1)
button3.grid(row=0, column=2)
button4.grid(row=0, column=3)
a = 1
elif a >= 1 and a <= 3:
for b in range(len(X0)):
for c in range(len(X0[0])):
X0[b][c] *= a
a += 1
else:
for b in range(len(X0)):
for c in range(len(X0[0])):
X0[b][c] *= a
a = 1
for i in range(len(X0)):
for j in range(len(Y0[0])):
for k in range(len(Y0)):
result0[i][j] += X0[i][k] * Y0[k][j]
agrp = LabelFrame(root, text="Process-0", padx=5, pady=5)
agrp.grid(row=2, column=1)
for r in range(3):
for c in range(4):
Label(agrp, text=result0[r][c],
borderwidth=4 ).grid(row=r,column=c)
root.after(1000, lambda x = a: update(x))
def win2():
board = Toplevel()
board.title("Message")
S = Scrollbar(board)
T = Text(board, height=4, width=50)
T.pack()
S.pack(side=RIGHT, fill=Y)
T.pack(side=LEFT, fill=Y)
S.config(command=T.yview)
T.config(yscrollcommand=S.set)
quote = """Yep, this is text"""
T.insert(END, quote)
root = Tk()
a=0
update(a)
root.mainloop()
The update method should only calculate and display changes.
def update(a):
if a == 0:
a = 1
elif a >= 1 and a <= 3:
for b in range(len(X0)):
for c in range(len(X0[0])):
X0[b][c] *= a
a += 1
else:
for b in range(len(X0)):
for c in range(len(X0[0])):
X0[b][c] *= a
a = 1
for i in range(len(X0)):
for j in range(len(Y0[0])):
for k in range(len(Y0)):
result0[i][j] += X0[i][k] * Y0[k][j]
for r in range(3):
for c in range(4):
Label(agrp, text=result0[r][c],
borderwidth=4 ).grid(row=r,column=c)
root.after(1000, lambda x = a: update(x))

Zeller's Algorithm with Tkinter Python

The code below is written to print out the day of the date wirtten which is called zellers algorithm. I tried to compile it with Tkinter but I get errors everytime.What is wrong with my code I would be glad if someone helps me. Error is:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1536, in __call__
return self.func(*args)
File "C:/Users/Ali/Desktop/zellers­revisited.py", line 60, in <lambda>
button = Tkinter.Button(zeller, text = "Show the day",command = lambda:zellers(A,B,C) )
File "C:/Users/Ali/Desktop/zellers­revisited.py", line 11, in zellers
D = int(str(C)[0:2])+1
ValueError: invalid literal for int() with base 10: ''
import math
import Tkinter
import tkMessageBox
dictionary = {"March": 1, "April":2, "May":3, "June":4, "July":5,"August":6, "September":7, "October":8, "November":9, "December":10 ,"January":11, "February":12}
def zellers(a,b,c):
a = int(str(c)[0:2])+1
a = int(dictionary[a])
a = int(str(c)[2:4])
w = ((13*a)-1) / 5
x = c / 4
y = d / 4
z = (w + x + y + b + c) - 2*d
r = z%7
if r == 0:
print "Sunday"
elif r == 1:
print "Monday"
elif r == 2:
print "Tuesday"
elif r == 3:
print "Wednesday"
elif r == 4:
print "Thursday"
elif r == 5:
print "Friday"
elif r == 6:
print "Sunday"
zeller = Tkinter.Tk()
month_label = Tkinter.Label(zeller ,text="Write the month: ")
entry1 = Tkinter.Entry()
a = entry1.get()
date_label = Tkinter.Label(zeller, text="Enter the date: ")
entry2 = Tkinter.Entry()
b = Entry2.get()
year_label = Tkinter.Label(zeller, text="Write the year: ")
entry3 = Tkinter.Entry()
c = Entry3.get()
button = Tkinter.Button(zeller, text = "Show the day",command = lambda:zellers(a,b,c) )
month_label.grid(row=0 , column=0)
entry1.grid(row=0, column=2)
date_label.grid(row=1, column=0)
entry2.grid(row=1, column=2)
year_label.grid(row=3, column=0)
entry3.grid(row=3, column=2)
button.grid(row=4, column=1)
zeller.mainloop()
The calls to get
Entry1 = Tkinter.Entry()
A = Entry1.get()
query the Entry widgets immediately, right after creation. Since they are empty at that point, A (and B and C) are empty strings.
You need to call get after zellers gets called:
def zellers():
A = Entry1.get()
B = Entry2.get()
C = Entry3.get()
...
import Tkinter
dictionary = {"March": 1, "April":2, "May":3, "June":4, "July":5,"August":6,
"September":7, "October":8, "November":9, "December":10 ,
"January":11, "February":12}
def zellers():
A = Entry1.get()
B = Entry2.get()
C = Entry3.get()
D = int(str(C)[0:2])+1
A = int(dictionary[A])
B = int(B)
C = int(str(C)[2:4])
W = ((13*A)-1) / 5
X = C / 4
Y = D / 4
Z = (W + X + Y + B + C) - 2*D
R = Z%7
result = {0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday',
5: 'Friday', 6: 'Saturday'}
print(result[R])
root = Tkinter.Tk()
month_label = Tkinter.Label(root ,text="Write the month: ")
Entry1 = Tkinter.Entry()
date_label = Tkinter.Label(root, text="Enter the date: ")
Entry2 = Tkinter.Entry()
year_label = Tkinter.Label(root, text="Write the year: ")
Entry3 = Tkinter.Entry()
button = Tkinter.Button(root, text = "Show the day", command=zellers)
month_label.grid(row=0, column=0)
Entry1.grid(row=0, column=2)
date_label.grid(row=1, column=0)
Entry2.grid(row=1, column=2)
year_label.grid(row=3, column=0)
Entry3.grid(row=3, column=2)
button.grid(row=4, column=1)
root.mainloop()

How do I backspace and clear the last equation and also a quit button?

I tried this:
self.btnquit = button(calc_frame, "Quit", tk.destroy)
self.btnquit.pack(side = LEFT)
before self.input = ...
But it came out invalid syntax. And the backspace only works if its in front of the number but I want it to be able to ackspace the last number entered, clear the last equation and then:
from tkinter import *
from tkinter.font import Font
def button(frame, text, command=None):
ft = Font(family=('Verdana'), size=14)
return Button(frame, text=text, font=ft, width=3, command=command)
def frame(frame, side=LEFT, bg="black"):
f = Frame(frame, background=bg, padx=5, pady=5)
f.pack(side=side, expand=YES, fill=BOTH)
return f
class App:
def __init__(self, tk):
ft = Font(family=('Verdana'), size=14)
main = frame(tk)
l_frame = frame(main)
r_frame = frame(main)
calc_frame = frame(l_frame)
self.input = Entry(calc_frame, font=ft, width=15, background="white")
self.input.pack(side=TOP)
self.btn_frame = frame(calc_frame)
x, y = 0, 0
for key in ("()%C", "+-*/", "1234", "5678", "90.="):
for c in key:
if c == "=":
btn = button(self.btn_frame, c, self.equalAction)
elif c == "C":
btn = button(self.btn_frame, c, self.cleanAction)
else:
btn = button(self.btn_frame, c, lambda i=c: self.input.insert(INSERT, i))
btn.grid(row=x, column=y)
y += 1
x += 1
y = 0
self.log = Text(r_frame, font=Font(family=('Verdana'), size=10), width=25, height=14, background="yellow")
self.log.pack(side=RIGHT)
def cleanAction(self):
self.input.delete(0, END)
def equalAction(self):
tmp = self.input.get()
try:
result = tmp + "=" + str(eval(tmp))
self.log.insert(1.0, result + "\n");
print(result)
except Exception:
self.log.insert(1.0, "Wrong expression\n");
if __name__ == '__main__':
root = Tk()
root.title("Calculator")
root.geometry()
app = App(root)
root.mainloop()
You can bind function to BackSpace in __init__
only when cursor (focus) is in Entry
self.input.bind_all('<BackSpace>', self.cleanInput)
or for all situations
main.bind_all('<BackSpace>', self.cleanInput)
and than you can delete text in Entry and Text
def cleanInput(self, event):
self.input.delete(0, END)
self.log.delete(1.0, END)
BTW: the same way you can bind other keys - for example digits
else:
btn = button(self.btn_frame, c, lambda i=c: self.input.insert(INSERT, i))
main.bind_all(c, lambda event, i=c:self.input.insert(INSERT, i))
EDIT:
full working code:
(issue: at that moment when cursor is in Entry numbers are inserted twice - normaly and by binding)
# python 2.x
#from Tkinter import *
#from tkFont import Font
# python 3.x
from tkinter import *
from tkinter.font import Font
class App:
def __init__(self, tk):
self.tk = tk
self.tk.title("Calculator")
#self.tk.geometry()
self.button_font = Font(family=('Verdana'), size=14)
main_frame = self.create_frame(self.tk)
left_frame = self.create_frame(main_frame)
right_frame = self.create_frame(main_frame)
calc_frame = self.create_frame(left_frame)
self.btnquit = self.create_button(calc_frame, "Quit", self.tk.destroy)
self.btnquit.pack(side = LEFT)
self.log = Text(right_frame, font=Font(family=('Verdana'), size=10), width=25, height=14, background="yellow")
self.log.pack(side=RIGHT)
self.input_text = StringVar()
self.input = Entry(calc_frame, font=self.button_font, width=15, background="white", textvariable=self.input_text)
self.input.pack(side=TOP)
btn_frame = self.create_frame(calc_frame)
for x, key in enumerate( ("()%C", "+-*/", "1234", "5678", "90.=") ):
for y, c in enumerate(key):
if c == "=":
btn = self.create_button(btn_frame, c, self.equalAction)
elif c == "C":
btn = self.create_button(btn_frame, c, self.cleanAction)
else:
btn = self.create_button(btn_frame, c, lambda number=c: self.insertNumber(number))
#main.bind_all(c, lambda event, number=c: self.insertNumber(number))
btn.grid(row=x, column=y)
self.btn_backspace = self.create_button(btn_frame, "<-", self.deleteLastDigit)
self.btn_backspace.grid(row=5, column=2, columnspan=2, sticky="we")
self.btn_loop = self.create_button(btn_frame, "LOOP", self.loopAction)
self.btn_loop.grid(row=5, column=0, columnspan=2, sticky="we")
main_frame.bind_all('<BackSpace>', self.cleanAction)
main_frame.bind_all('<Escape>', self.deleteLastDigit)
def loopAction(self):
bedmas = [ "()", "x^n", "*/", "+-" ]
for element in bedmas:
self.log.insert(INSERT,"\n"+element)
# event=None to use function in command= and in binding
def deleteLastDigit(self, event=None):
self.input_text.set( self.input_text.get()[:-1] )
def insertNumber(self, number):
self.input_text.set( self.input_text.get() + number )
def cleanAction(self):
self.input_text.set("")
self.log.delete(1.0, END)
def equalAction(self):
tmp = self.input_text.get()
try:
result = tmp + "=" + str(eval(tmp))
self.log.insert(1.0, result + "\n");
print(result)
except Exception:
self.log.insert(1.0, "Wrong expression\n");
def create_button(self, frame, text, command=None):
return Button(frame, text=text, font=self.button_font, width=3, command=command)
def create_frame(self, frame, side=LEFT, bg="black"):
f = Frame(frame, background=bg, padx=5, pady=5)
f.pack(side=side, expand=YES, fill=BOTH)
return f
def run(self):
self.tk.mainloop()
#---------------------------------------------------------------------
if __name__ == '__main__':
App(Tk()).run()

Categories

Resources