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()
Related
This will draw a grid with same picture in every field. If I want to input row=x and col=y ex. x=3 y=2 and change picture only for that cell, how to do it?
Also if, I move that picture one or two fields how to get coordinates from cell where is it?
from tkinter import *
from PIL import Image, ImageTk
#main window
root = Tk()
root.title("toys ")
root.geometry("1000x800")
root.iconbitmap('Images/python.ico')
img1_temp = Image.open("Images/Spikes.png")
img1resized= img1_temp.resize((100,100))
img1 = ImageTk.PhotoImage(img1resized)
img2 = ImageTk.PhotoImage(Image.open("Images/Empty.png"))
imgr_temp = Image.open("Images/robot.png")
imgr_resized = imgr_temp.resize((100,100))
img_robot = ImageTk.PhotoImage(imgr_resized)
main_canvas = Canvas(root, width=600, height=600,scrollregion = "0 -200 200 0")
main_canvas.pack(pady=70)
cells = []
for r in range(6):
for c in range(6):
cells.append(Label(main_canvas, bd=5, height=80, width=80,
relief=RIDGE,padx=3, pady=3, image=img2).grid(row=r,column=c))
I tried this, but... not good
for cell in cells:
if type(cell) is Label:
row = 0
column = 0
image = img_robot
enter image description here
As you can see in the screenshot, my program has white lines on the left and top, how can I remove them? I would like them not to be there at all.
import ctypes as ct
from tkinter import *
def dark_title_bar(window):
window.update()
DWMWA_USE_IMMERSIVE_DARK_MODE = 20
set_window_attribute = ct.windll.dwmapi.DwmSetWindowAttribute
get_parent = ct.windll.user32.GetParent
hwnd = get_parent(window.winfo_id())
rendering_policy = DWMWA_USE_IMMERSIVE_DARK_MODE
value = 2
value = ct.c_int(value)
set_window_attribute(hwnd, rendering_policy, ct.byref(value), ct.sizeof(value))
win = Tk()
background_menu = PhotoImage(file="background-menu.png")
canvas_authorization = Canvas(win, width=1280, height=720)
canvas_authorization.grid()
canvas_authorization.create_image(640, 360, image=background_menu)
dark_title_bar(win)
win.geometry("1280x720")
win.geometry(str(win.winfo_width()+1) + "x" + str(win.winfo_height()+1))
#Returns to original size
win.geometry(str(win.winfo_width()-1) + "x" + str(win.winfo_height()-1))
win.geometry("1280x720")
win.mainloop()
I want to display multiple csv files (3 at least) in the same tkinter window but I have no clue how to do it. I have only found codes to display a single file in a window.
My current level in python is quite low (I'm a healthcare professional trying to do basic stuff) and it's basically adding together some code found online here and there but I still understand simple functions such as buttons and windows.
I have uploaded a picture to show more accurately what I'm aiming for: My goal in tkinter
Here is my current and my attempts so far:
from tkinter import *
import tkinter
import tkinter.ttk as ttk
from tkinter import Frame
import csv
root = tkinter.Tk()
root.title("Python - Healthcare continuity")
width = 500
height = 400
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
root.geometry("%dx%d+%d+%d" % (width, height, x, y))
root.resizable(0, 0)
TableMargin = ttk.Frame(root)
TableMargin.grid(column=0, row=0, sticky=(N, W, E, S))
scrollbarx = Scrollbar(TableMargin, orient=HORIZONTAL)
scrollbary = Scrollbar(TableMargin, orient=VERTICAL)
# open file
with open("open(first.csv,'r+',encoding='utf-8')", newline = "") as file:
reader = csv.reader(file)
# r and c tell us where to grid the labels
r = 0
for col in reader:
c = 0
for row in col:
# i've added some styling
label = tkinter.Label(root, width = 10, height = 2, \
text = row, relief = tkinter.RIDGE)
label.grid(row = r, column = c)
c += 1
r += 1
with open("second.csv", newline = "") as file:
reader = csv.reader(file)
# r and c tell us where to grid the labels
r = 0
for col in reader:
c = 0
for row in col:
# i've added some styling
label = tkinter.Label(root, width = 10, height = 2, \
text = row, relief = tkinter.RIDGE)
label.grid(row = r, column = c)
c += 1
r += 1
with open("third.csv", newline = "") as file:
reader = csv.reader(file)
# r and c tell us where to grid the labels
r = 0
for col in reader:
c = 0
for row in col:
# i've added some styling
label = tkinter.Label(root, width = 10, height = 2, \
text = row, relief = tkinter.RIDGE)
label.grid(row = r, column = c)
c += 1
r += 1
root.mainloop()
Thank you for your help.
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
I am attempting to create a python script to calculate the shortest trip around a set of colleges. i need to add a starting point, but ive confused myself beyond belief to the point of no return. Can anyone help me figure out where to go from here
from Tkinter import *
import tkMessageBox, tkFileDialog
import json
import re
from urllib import urlopen
import math
class Application(Frame):
collegelist = []
collegelist1 = []
def __init__(self,master=None):
Frame.__init__(self,master)
self.pack()
self.createWidgets()
def createWidgets(self):
self.top_frame = Frame(self)
self.mid_frame = Frame(self)
self.bot_frame = Frame(self, bg = 'red')
self.top_frame.pack(side = 'top')
self.mid_frame.pack(side = 'top')
self.bot_frame.pack(side = 'top')
#top frame
self.label1 = Label(self.top_frame, text = "Your College Choices", bg ='red')
self.label1.pack(side = 'left', padx='40', pady='0')
self.label2 = Label(self.top_frame, text = "Your Tour Selections", bg ='green')
self.label2.pack(side = 'right', padx='40')
#mid frame
self.mylist = Listbox(self.mid_frame,
bg = 'black',
fg = 'gold')
self.mylist.pack(side='left')
self.my_button1 = Button(self.mid_frame, text = '>>>', command=self.getlist)
self.my_button2 = Button(self.mid_frame, text = '<<<', command=self.returnlist)
self.my_button1.pack(side="left")
self.my_button2.pack(side="left")
self.mylist1 = Listbox(self.mid_frame,
selectmode=DISABLED,
bg = 'black',
fg = 'gold')
self.mylist1.pack(side='right')
#bottom frame
self.openbutton = Button(self.bot_frame, text='Open File', command=self.openfile, fg ='green')
self.openbutton.pack(side='left')
self.my_button = Button(self.bot_frame, text = 'Route', fg ='green', command=self.collegeroute)
self.my_button.pack(side='left')
self.quit_button = Button(self.bot_frame, text = 'Quit',
command = self.quit, fg = 'green')
self.quit_button.pack(side='left')
def openfile(self):
filename = tkFileDialog.askopenfilename(title='Choose a file')
if filename:
clist = open(filename, "r")
for line in clist.readlines():
for i in line.split():
self.collegelist.append(i)
for college in self.collegelist:
self.mylist.insert(1,college)
def getlist(self):
# get selected line index
index = [int(x) for x in self.mylist.curselection()]
print index
for i in index:
seltext = self.mylist.get(i)
self.mylist.delete(i)
self.mylist1.insert(1,seltext)
self.collegelist1.append(seltext)
print seltext
def returnlist(self):
# get selected line index
index = [int(x) for x in self.mylist1.curselection()]
for i in index:
seltext = self.mylist1.get(i)
self.mylist1.delete(i)
seltext = seltext.strip()
seltext = seltext.replace(' ', '')
self.mylist.insert(0,seltext)
self.collegelist1.remove(seltext)
def collegeroute(self):
# get selected line index
global tuplist
self.tuplist =[]
for college in self.collegelist1:
f = urlopen('http://graph.facebook.com/%s' % college) #load in the events
d = json.load(f)
longitude = d["location"]["longitude"]
latitude = d["location"]["latitude"]
name = d['name']
self.tuplist.append((latitude, longitude))
cartesian_matrix(self.tuplist)
def cartesian_matrix(coords):
'''create a distance matrix for the city coords
that uses straight line distance'''
matrix={}
for i,(x1,y1) in enumerate(coords):
for j,(x2,y2) in enumerate(coords):
dx,dy=x1-x2,y1-y2
dist=math.sqrt(dx*dx + dy*dy)
matrix[i,j]=dist
tour_length(matrix,collegelist1)
return matrix
def tour_length(matrix,tour):
total=0
num_cities=len(tour)
print tour
print num_cities
for i in range(num_cities):
j=(i+1)%num_cities
city_i=tour[i]
city_j=tour[j]
total+=matrix[city_i,city_j]
print total
def getRad(x):
return float(x) * (math.pi/180.0)
def main():
app = Application()
app.master.title("My Application")
app.mainloop()
if __name__ == "__main__":
main()
Having trouble getting the tour_length to work
You are calling tour_length and returning from cartesian_matrix in the wrong place. You are only doing one row of the matrix, then calling tour_length and returning.
Having trouble getting the tour_length to work
The only obvious problem with tour_length that I see is that you're failing to return the result. Add the following at the end:
return total
Upon closer inspection, the following also looks suspect:
tour_length(matrix,collegelist1)
return matrix
Firstly, it's mis-indented. Secondly, you're ignoring the return value of tour_length.
The mis-indentation is probably what's causing the exception (you're calling tour_length before you have fully initialized matrix).