Related
I have following Problem:
I have a table in which I documented which label for which article is needed.
The needed label should be updated automaticly when the entry is changed.
I look in a dataframe for the article number and give back the neede lable as picture.
For some reason it works only one time, and only if I enter with copy and paste the right article number. after the first time always the exept value is set to my variable.
I also don't understand the meaning of the *args as input for my search_label function. But without it gave me as soon as I entered something in the entry field the error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python\Python_3.9.1\lib\tkinter\__init__.py", line 1884, in __call__
return self.func(*args)
TypeError: search_label() takes 0 positional arguments but 3 were given
from multiprocessing import Process
import tkinter as tk
import pandas as pd
from PIL import ImageTk, Image
import os
import tkinter.messagebox as tkmb
def display_img(img_src):
global img
img = Image.open(img_src)
'size of the picture'
width_hight = 180
img = img.resize((width_hight, width_hight))
img = ImageTk.PhotoImage(img)
panel = tk.Label(root, image=img, bd=0)
'place in the middle of the window'
panel.place(x=width / 2 - width_hight / 2, y=row3)
def search_label(*args):
try:
artikel = entry_var.get()
artikel = str(artikel).upper()
print('entry= ', artikel)
#Needed cols of Excelfile
cols = ['Nr_','Reinigungsmittel']
global df
df = pd.DataFrame(df, columns=cols)
#For some reason there are always spaces at the end of the artikel in the dataframe
#remove spaces
df['Nr_'] = df['Nr_'].str.strip()
df.to_csv('Reinigungsmittel.csv', sep= ";", encoding='utf-8-sig')
df = df.set_index('Nr_')
#filter the dataframe only for artikel number
print('df:')
print(df)
#make entry capital letters
df_reinigungsmittel = df.loc[[artikel]]
#get only the cleanning article
cleaning_article = str(df_reinigungsmittel.iloc[0][0])
print('ergebnis:')
print(cleaning_article)
cleaning_article = str(cleaning_article).strip()
except:
cleaning_article = 'label search failed'
evaluation(cleaning_article)
def evaluation(cleaning_article):
print('input evaluation:',cleaning_article)
if cleaning_article == 'CMETHANOL':
cleaning_article = 'rot.png'
elif cleaning_article == 'CPROPANOL2':
cleaning_article = 'gruen.png'
elif cleaning_article == 'CPROPANOL':
cleaning_article = 'blau.png'
else:
cleaning_article = 'non.png'
print(cleaning_article)
display_img(cleaning_article)
#load dataframe when program is opend, so the dataframe doent' need to be loaded for each search
datasource = r'C:\Arbeit\scripte\Reinigungslabel\Reinigungslabel.xlsx'
datasource_csv = r'C:\Arbeit\scripte\Reinigungslabel\Reinigungsmittel.csv'
#df = pd.read_excel(datasource)
df = pd.read_csv(datasource_csv, sep =';')
# Window and layout settings
hight = 270
width = 250
column_space = 5
column1 = 10
width_column1 = width - 20
#start value of cleaning_article
cleaning_article = 'non.png'
hight_row = 30
space_row = 5
row1 = 10
row2 = row1 + hight_row + space_row
row3 = row2 + hight_row + space_row
root = tk.Tk()
entry_var = tk.StringVar()
entry_var.trace('w',search_label)
print(df)
root.title("Reinigungs Label V1.0")
# get screen width and height
# width of the screen
ws = root.winfo_screenwidth()
# height of the screen
hs = root.winfo_screenheight()
# calculate x and y coordinates for the Tk root window
x = ws - (1.05 * width)
y = 30
root.geometry('%dx%d+%d+%d' % (width, hight, x, y))
root.configure(bg='black', bd=0)
Canvas = tk.Canvas(root, height=hight, width=width).place()
frame_artikel = tk.Frame(root, bg = 'black')
frame_artikel.place(x=column1, y=row1, width=width_column1, height=hight_row)
entry_artikel = tk.Entry(frame_artikel, textvariable=entry_var, font=20)
entry_artikel.focus()
entry_artikel.place(relwidth=1, relheight=1)
root.mainloop()
This question already has answers here:
Setting background color of a tkinter ttk frame
(3 answers)
Closed 3 years ago.
I want to change the background of my ttk form (ceasar code script) to the color I have in my window = #FEFB22
I want to change the white "box" color to #FEFB22 click to see image !
from tkinter import *
from tkinter import ttk
# variables
letters="ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
# fenetre
root = Tk()
#window title
root.title('Cesar Crypt/Decrypt par Maxence')
root.iconbitmap("logo.ico")
# allows for window to be resized
root.geometry("850x480")
# window background
root.configure(background='#FEFB22')
root.frame_header = ttk.Frame()
ttk.Label(root.frame_header, text = 'Code César', style = 'Header.TLabel').grid(row = 0, column = 1)
ttk.Label(root.frame_header, text = 'Entrez un nombre entre 1 et 25 :', style = 'Header.TLabel').grid(row = 1, column = 0)
ttk.Label(root.frame_header, text = 'Votre Message:', style = 'Header.TLabel').grid(row = 2, column = 0)
ttk.Label(root.frame_header, text='Votre message crypté/decrypté:',style='Header.TLabel').grid(row=4, column=0)
enc_dec_text = ttk.Entry(root.frame_header, width=110)
enc_dec_text.grid(row=4,column=1)
cipher_shift_menu = StringVar()
Spinbox(root.frame_header,from_=1, to=25, textvariable=cipher_shift_menu).grid(row=1, column=1)
text_entry = ttk.Entry(root.frame_header, width=100)
text_entry.grid(row=2,column=1)
def encrypt_text():
stringtoencrypt = text_entry.get()
stringtoencrypt = str(stringtoencrypt)
stringtoencrypt=stringtoencrypt.upper()
ciphershift = cipher_shift_menu.get()
ciphershift=int(ciphershift)
stringencrypted=""
for character in stringtoencrypt:
position = letters.find(character)
newposition = position+ciphershift
if character in letters:
stringencrypted = stringencrypted + letters[newposition]
else:
stringencrypted = stringencrypted + character
enc_dec_text.insert(0, stringencrypted)
def decrypt_text():
stringtodecrypt = text_entry.get()
stringtodecrypt = str(stringtodecrypt)
stringtodecrypt=stringtodecrypt.upper()
ciphershift = cipher_shift_menu.get()
ciphershift=int(ciphershift)
stringdecrypted=""
for character in stringtodecrypt:
position = letters.find(character)
newposition = position-ciphershift
if character in letters:
stringdecrypted = stringdecrypted + letters[newposition]
else:
stringdecrypted = stringdecrypted + character
enc_dec_text.insert(0, stringdecrypted)
#add image
width = 200
lenght = 200
image = PhotoImage(file="logort.png")
#bouton image
button = Button(root, image=image, bg='#FEFB22', bd=0, relief=SUNKEN)
button.pack()
# boutous
encrypt_button = ttk.Button(root.frame_header,text='Encrypter',command = lambda: encrypt_text()).grid(row=3,column=0)
decrypt_button = ttk.Button(root.frame_header,text='Decrypter',command = lambda: decrypt_text()).grid(row=3,column=1)
#bouton q
# uitter
bouton_quitter = Button(root, text="Quitter !", command=root.quit, font=("Courrier", 20), bg='#000000', fg='#FEFB22')
bouton_quitter.pack(side=BOTTOM)
root.frame_header.pack()
root.mainloop()
You can use ttk.Style to change the frame background color:
s = ttk.Style()
s.configure('My.TFrame', background='#FEFB22')
root.frame_header = ttk.Frame(root, style='My.TFrame')
I am constructing a messaging application, and using Tkinter for GUI. I am trying to create some buttons, but I receive an error message:
Traceback (most recent call last):
File "/home/artur/Documents/MScProject/MSc Project/Task #179276/main_program.py", line 174, in <module>
app = Application(the_window)
File "/home/artur/Documents/MScProject/MSc Project/Task #179276/main_program.py", line 49, in __init__
self.AES_radiobutton = Radiobutton(text = 'AES algorithm', bg = color, variable=self.var, value=0)
NameError: name 'Radiobutton' is not defined
I am posting all of the source code here:
import tkinter as tk
from tkinter import IntVar
from tkinter import messagebox
from tkinter import Frame
from tkinter import Frame
from tkinter import Text
from tkinter import Label
from AESEncDec import *
from MD5Hashing import *
from RSAEncDec import *
color = 'lightblue' #color our background
class Application(Frame):
def __init__(self, root=None):
Frame.__init__(self, root)
self.frame_width = 700
self.frame_height = 400
# Set configuration our frame
self.config(width = self.frame_width, height = self.frame_height, bg = color)
self.pack()
# Create textBox for input data
self.textbox_one = Text()
self.textbox_one.place(x = 30, y = 170, height = 200, width = 300 )
# Create textBox for result
self.textbox_two = Text()
self.textbox_two.place(x = 370, y = 170, height = 200, width = 300 )
label_input_text = Label( text = "Input text: ", bg = color)
label_input_text.place(x = 30, y = 155, height = 10, width = 70 )
label_output_text = Label( text = "Result: ", bg = color)
label_output_text.place(x = 370, y = 155, height = 10, width = 50 )
# IntVar help to detect, what radioButton was chosen
self.var = IntVar()
# Create radioButton for AES
self.AES_radiobutton = Radiobutton(text = 'AES algorithm', bg = color, variable=self.var, value=0)
self.AES_radiobutton.place(x = 100, y = 20, height = 30, width = 100 )
# Create radioButton for DSA
self.DSA_radiobutton = Radiobutton(text = 'DSA algorithm', bg = color, variable=self.var, value=1)
self.DSA_radiobutton.place(x = 100, y = 70, height = 30, width = 100 )
# Create radioButton for Hash function
self.HF_radiobutton = Radiobutton(text = 'Hash function', bg = color, variable=self.var, value=2)
self.HF_radiobutton.place(x = 100, y = 120, height = 30, width = 100 )
# Create label
self.lable_for_ask_bits = Label(text = 'Input size of bits:', bg = color)
self.lable_for_ask_bits.place(x = 210, y = 70, height = 30, width = 100 )
# Create textBox for input bits
self.input_bits = Text()
self.input_bits.place(x = 310, y = 75, height = 20, width = 50 )
self.input_bits.insert(INSERT, '16')
# Create button to encrypt text
self.encrypt_button = Button(root, text = "Encrypt text", command = self.encrypt_text)
self.encrypt_button.place(x = 420, y = 20, height = 80, width = 100 )
# Create button to decrypt text
self.decrypt_button = Button(root, text = "Decrypt text", command = self.decrypt_text)
self.decrypt_button.place(x = 540, y = 20, height = 80, width = 100 )
# Create button to hash
self.hash_button = Button(root, text = "Hash text", command = self.hashing )
self.hash_button.place(x = 420, y = 120, height = 30, width = 220)
# Create AES object, keyword "this is a very strong key"
# You can change keyword
self.AES = AESEncDec('this is a very strong key')
# Save bits
self.bit_length = 16
# Create RSA object
self.RSA = RSAEncDec(self.bit_length)
def encrypt_text(self):
self.textbox_two.delete("1.0", END)
# Get radioButton selection
selection = self.var.get()
# if chosen AES
if selection == 0:
# Read text from input
message = self.textbox_one.get("1.0", END)
encrypt_message = self.AES.encrypt(message)
# Output result
self.textbox_two.insert(INSERT, encrypt_message)
# if chosen RSA
elif selection == 1:
try:
# Read number of bits
tmp_bits = int(self.input_bits.get("1.0", END))
# if bits not in range from 4 to 32 print error message
if tmp_bits < 4 or tmp_bits > 32:
tkMessageBox.showerror(message ='Bits must be in range from 4 to 32')
else:
# else, if tmp_bits not = self.bit_length: create new object
if tmp_bits != self.bit_length:
self.bit_length = tmp_bits
self.RSA = RSAEncDec(self.bit_length)
except:
tkMessageBox.showerror(message ='You must input integer number')
# Find max number
max_number = self.RSA.get_max_value_to_encrypt()
try:
# Read text from input (myst be number)
message = int(self.textbox_one.get("1.0", END))
if message < 0 or message > max_number:
tkMessageBox.showerror(message ='Input text must be number in range from 0 to ' + str(max_number))
else:
encrypt_message = self.RSA.encrypt(message)
# Output result
self.textbox_two.insert(INSERT, encrypt_message)
except:
tkMessageBox.showerror(message ='Input text must be number in range from 0 to ' + str(max_number))
else:
tkMessageBox.showinfo(message ='You must select "AES" or "RSA" radioButton')
def decrypt_text(self):
self.textbox_two.delete("1.0", END)
# Get radioButton selection
selection = self.var.get()
# if chosen AES
if selection == 0:
# Read text from input
message = self.textbox_one.get("1.0", END)
decrypt_message = self.AES.decrypt(message)
# Output result
self.textbox_two.insert(INSERT, decrypt_message)
elif selection == 1:
# Read text from input
message = int(self.textbox_one.get("1.0", END))
decrypt_message = self.RSA.decrypt(message)
# Output result
self.textbox_two.insert(INSERT, decrypt_message)
else:
tkMessageBox.showinfo(message ='You must select "AES" or "RSA" radioButton')
def hashing(self):
# Get radioButton selection
selection = self.var.get()
# if chosen Hash function
if selection == 2:
# Read text from input
message = self.textbox_one.get("1.0", END)
# Hashing
hashing_message = Hashing(message)
# Output result
self.textbox_two.insert(INSERT, hashing_message)
else:
tkMessageBox.showinfo(message ='You must select "Hash function" radioButton')
#create object TK class
the_window = tk.Tk(className = " Cryptographic")
#create object Application
app = Application(the_window)
#run our Application
app.mainloop()
I still see the GUI though and an input box, but a lot of elements are missing. What might be the problem here?
Simple import of Radiobutton module solved the issue
This is my current code and it displays in a window but literally prints it the way I've typed it (obviously). But is there a way to write these so they are displayed as powers/exponents?
"
questionNum = 0
#SET QUESTIONS HERE
questions = [0,"Given that y = x^4 + 6x^1/2, find dy/dx","Write down the value of 125^1/3","Fully factorise 9x^2 - 25","Find the value of 8^5/3"]
answer1 = [0,"4x^4 + 3x^1/2","25","(3x-5)(3x+5)","1/2"]
answer2 = [0,"4x^3 + 6x^1/2","1/5","(3x+5)(3x+5)","Answer 2 (4)"]
answer3 = [0,"4x^3 + 6x^-1/2","5","(3x-5)(3x-5)","Answer 3 (4)"]
answer4 = [0,"4x^3 + 1/2x^-3/2","125","(9x+5)(x-5)","Answer 4 (4)"]
This is what it looks like:
rightanswers = [0,1,2,3,4] #These are the correct answers
"
This is the bit that needs to be changed. I've added the rest just in case you need any of it to see what's going on:
from tkinter import * #The TKinter module imported in order to create the menus
import sys #Invoke functions and statements - allows operations to work and searches for named modules i.e. TKinter
global questionNum #Connections between functinos and arrays
questionNum = 0
#SET QUESTIONS HERE
questions = [0,"Given that y = x^4 + 6x^1/2, find dy/dx","Write down the value of 125^1/3","Fully factorise 9x^2 - 25","Find the value of 8^5/3"] #This is the question bank which has been set up as an array
answer1 = [0,"4x^4 + 3x^1/2","25","(3x-5)(3x+5)","1/2"] #These are the possible answers - this is where multiple choice answers would go
answer2 = [0,"4x^3 + 6x^1/2","1/5","(3x+5)(3x+5)","Answer 2 (4)"]
answer3 = [0,"4x^3 + 6x^-1/2","5","(3x-5)(3x-5)","Answer 3 (4)"]
answer4 = [0,"4x^3 + 1/2x^-3/2","125","(9x+5)(x-5)","Answer 4 (4)"]
rightanswers = [0,1,2,3,4] #These are the correct answers
normal = Tk() #Build the TKinter
normal.geometry("850x350") #Set the size of the normal chess form to 850x350
normal.title("Normal Chess") #Sets a title for the normal chess form
normal.columnconfigure(1,minsize = 300) #This is whereabouts the question and answers are displayed
questionVar = StringVar() #Question will be a string
answerVar = IntVar() #Answers will be numbers
answerVar.set(1) #Questions can only have one solution
aText = StringVar() #Text for the answers - options
bText = StringVar()
cText = StringVar()
dText = StringVar()
qNoText = StringVar() #Questions text which is displayed to the user
questionText = StringVar()
normal.withdraw() #Allows the user to only select one option
title = Tk() #Builds the TKinter
title.title("Chess") #Title of the form
title.geometry("300x300") #The size of the image
watermark = PhotoImage(file = "watermark.gif") #Link to the image itself
Label(image = watermark).place(x=0,y=0,relwidth=1,relheight=1) #Places the image onto the form set on the x,y coordinates
title.withdraw()
menu = Tk() #Builds the TKinter
menu.title("Main Menu") #Displays 'Main Menu' on screen
menu.geometry("400x350") #Size of the form
p1var = StringVar() #Sets a variable for Player 1 and Player 2
p2var = StringVar()
def Quit(): #Quit function - allows the user to exit the program
menu.destroy()
title.destroy()
normal.destroy()
sys.exit() #Gets rid of all the modules
def play():
title.deiconify()
Label(title,text = "Enter Details:",font = ("Calibri",25)).grid(row = 1, column = 1)
#'Enter Details' font, size and location on the form
Label(title,text = "CHESS",font = ("Calibri",50)).grid(row = 0,column = 1)
#'CHESS' font, size and location on the form
Label(title, text = "Player 1: ").grid(row = 2,column = 0)
#'Player 1' font, size and location on the form
Entry(title,textvariable = p1var,width = 30).grid(row = 2,column = 1)
#Allows the user to input a string for the player 1 name
Label(title, text = "Player 2: ").grid(row = 3,column = 0)
#'Player 2' font, size and location on the form
Entry(title,textvariable = p2var,width = 30).grid(row = 3,column = 1)
#Allows the user to input a string for the player 2 name
Label(title,text = "Select Game Mode: ").grid(row = 4,column = 1)
#'Select Game Mode: ' font, size and location on the form
Button(title,command = lambda: playNormalChess(p1var.get(),p2var.get()),text = "Normal Chess").grid(row = 6,column = 1,sticky = W)
#Button for normal chess
Button(title,command = lambda: playSpeedChess(p1var.get(),p2var.get()),text = "Speed Chess").grid(row = 6,column = 1,sticky = E)
#Button for speed chess
Button(title,command = instructions,text = "Instructions").grid(row = 7,column = 1,pady =10)
#Button for instructions
def playNormalChess(p1,p2):
normal.deiconify()
t = Label(textvariable = qNoText,font = ("Arial",50)).grid(row = 0,column = 1,sticky = W,columnspan=2,padx = 20,pady =10)
#Functions for selection
q =Label(textvariable = questionVar,font = ("Arial",30)).grid(row = 1,column = 1,sticky = W,columnspan=2,padx = 20,pady =10)
#Font and size the questions are set in
a=Radiobutton(variable = answerVar,value = 1,textvariable = aText,font = ("Arial",18)).grid(row = 3,column = 1,pady =5,padx = 20,sticky = W)
#These are the radio buttons which are linked to the answers - set the font and the size of the text
b=Radiobutton(variable = answerVar,value = 2,textvariable = bText,font = ("Arial",18)).grid(row = 4,column = 1,padx = 20,sticky = W)
c=Radiobutton(variable = answerVar,value = 3,textvariable = cText,font = ("Arial",18)).grid(row =5,column = 1,pady = 5,padx = 20,sticky = W)
d=Radiobutton(variable = answerVar,value=4,textvariable = dText,font = ("Arial",18)).grid(row = 6,column = 1,padx = 20,sticky = W)
Button(text = "Submit",command = confirm).grid(row =0,column = 3,sticky = W,pady = 10) #Submit button to confirm their answers
newQuestion() #Calls the function for a new question
def confirm():
if messagebox.askyesno('Confirm','Are You Sure?'): #This is the conformation of the correct answer for the user
try:
if answerVar.get() == rightanswers[questionNum]: #If they select yes to confirm they are happy with the selection
# - it checks their answer with the correct answer and prints 'Right' or 'Wrong' depending on their answer
print("Right")
else:
print("Wrong")
newQuestion() #Once their question is answered, a new question will be presented to them
except IndexError:
print("No more Questions")
def newQuestion():
global questionNum
questionNum = questionNum + 1
try:
qNoText.set("Question "+str(questionNum))
aText.set(answer1[questionNum])
bText.set(answer2[questionNum])
cText.set(answer3[questionNum])
dText.set(answer4[questionNum])
questionVar.set(questions[questionNum])
except IndexError:
print("No more questions")
Label(menu,text = "AS Maths Chess",font = ("Arial",37)).pack(pady = 20)
Button(menu,text = "Play",background = "black",foreground = "white",font = ("Arial",20),command = play).pack(ipadx = 80,ipady = 20, pady = 10)
Button(menu,text = "Quit",font = ("Arial",20),command = Quit).pack(ipadx = 80,ipady = 20, pady = 10)
Unicode has superscript numerals, arithmetic operators, and some letters in the BMP, which is supported by tcl/tk. See Wikipedia. Within those constraints, and given a supporting font, the answer is yes. On Windows, running from IDLE, the following works nicely and looks nice, though I would want the tk font larger to see the superscript easily with my eyes.
import tkinter as tk
root = tk.Tk()
# "4x^4 + 3x^1/2"
t1 = "4x\u2074 + 3x\u207b\u00b2" # \u excapes, if needed
t2 = "4x⁴ + 3x⁻²"
label = tk.Label(root, text=t2)
label.pack()
I am a python newbie and have been making a somewhat odd slideshow script that cycles through images and also sources a variable from another file to 'settle' on an image.
I'm sure my code is tragic. But it does work (see below)!
My question is - how would I make it fade between images instead of the jerky go to white momentarily then to next image which it does currently? Is there a transitions module I should look at?
from Tkinter import *
import Image, ImageTk, random, string
class MyApp(Tk):
def __init__(self):
Tk.__init__(self)
fr = Frame(self)
fr.pack()
self.canvas = Canvas(fr, height = 400, width = 600)
self.canvas.pack()
self.old_label_image = None
self.position = 0
self.command = 0
self.oldcommand = 0
self.slideshow()
self.debug()
def debug(self):
self.QUIT = Button(self)
self.QUIT["text"] = "QUIT!" + str(self.command)
self.QUIT["fg"] = "red"
self.QUIT["command"] = self.quit
self.QUIT.pack({"side": "right"})
def slideshow (self):
if self.command != self.oldcommand:
self.after_cancel(self.huh)
# run through random between 2-5 changes
# then settle on command for 30 seconds
self.title("Title: PAUSE")
self.oldcommand = self.command
self.slideshow()
else:
file = str(self.position) + '.jpg'
image1 = Image.open(file)
self.tkpi = ImageTk.PhotoImage(image1)
label_image = Label(self, image=self.tkpi)
label_image.place(x=0,y=0,width=image1.size[0],height=image1.size[1])
self.title("Title: " + file)
if self.old_label_image is not None:
self.old_label_image.destroy()
self.old_label_image = label_image
# make this random instead of pregressional
if self.position is not 1:
self.position = self.position + 1
else:
self.position = 0
commandfile = open('command.txt', 'r')
self.command = string.atoi(commandfile.readline())
commandfile.close()
int = random.randint(2000, 5000)
self.huh = self.after(int, self.slideshow)
#self.after_cancel(huh) - works ! so maybe can do from below Fn?
if __name__ == "__main__":
root = MyApp()
root.mainloop()
This can be achieved using the blend function.
Image.blend(image1, image2, alpha) ⇒ image
Creates a new image by interpolating between the given images, using a constant alpha. Both images must have the same size and mode.
out = image1 * (1.0 - alpha) + image2 * alpha
If the alpha is 0.0, a copy of the first image is returned. If the alpha is 1.0, a copy of the second image is returned. There are no restrictions on the alpha value. If necessary, the result is clipped to fit into the allowed output range.
So you could have something like this:
alpha = 0
while 1.0 > alpha:
image.blend(img1,img2,alpha)
alpha = alpha + 0.01
label_image.update()
An example is here, havn't had time to test this but you get the idea-
from PIL import image
import time
white = image.open("white_248x.jpg")
black = image.open("black_248x.jpg")
new_img = image.open("white_248x.jpg")
root = Tk()
image_label = label(root, image=new_img)
image_label.pack()
alpha = 0
while 1.0 > alpha:
new_img = image.blend(white,black,alpha)
alpha = alpha + 0.01
time.sleep(0.1)
image_label.update()
root.mainloop()