customerqtyUI = Label(homeUI, text = (str('number of customer:'), customer) , font = ('calibri', 20), background="floral white", foreground = 'black')
this is my code👆.
May i know why i cannot combine the string and my variable 'customer' together?
My output👆 will have a {} and i cannot remove it
I'm not sure how tkinter works, but in this case, you've passed a tuple consisting of str('number of customer:') and customer to the text keyword argument. What you really want to do is combine 'number of customers:' with the customer variable. Try this:
customerqtyUI = Label(homeUI, text = f'number of customer: {customer}', font = ('calibri', 20), background="floral white", foreground = 'black')
text field accepts a string. Passing a tuple (or any other type) will be counted as undefined behaviour. So the solution becomes
Label(..., text = 'number of customer: ' + str(customer), ...)```
Related
I have the following bits of code that creates a toplevel window and parses a dictionary into a Text widget:
def escrito(**kwargs):
write_window = Toplevel(root)
#write_window.title(kwargs) (problematic code)
writing_box = tk.Text(write_window, font = ("calibri", 20), width = 60, height = 15, wrap=WORD)
writing_box.pack(expand = tk.YES, fill = tk.X)
writing_box.grid(row = 0, column = 0, sticky = 'nswe')
texto = '\n'.join(key + ":\n" + value for key, value in kwargs.items())
writing_box.insert("1.0", texto)
def septic_osteo():
escrito(**infections.Septic_arthritis)
Septic_arthritis = {
'Empirical Treatment':
'Flucloxacillin 2g IV 6-hourly',
'If non-severe penicillin allergy':
'Ceftriaxone IV 2g ONCE daily',
'If severe penicillin allergy OR if known to be colonised with
MRSA':
'Vancomycin infusion IV, Refer to Vancomycin Prescribing
Policy',
'If systemic signs of sepsis': 'Discuss with Consultant
Microbiologist'
}
So when I run the code, the escrito functions parses the dictionary and writes its content onto a text widget contained on a Toplevel window. What I would like to know is how to dynamically rename the Toplevel window with the dicitonary's name. I do know that I can do this:
def septic_osteo():
escrito(**infections.Septic_arthritis)
write_window.title('Septic_arthritis)
but I do have like 100 functions like the one above, so, aside from labour intensive, I am not sure is the more pythonic way, so, is there a way that the window can be renamed with the dictionary name? (i.e. 'Septic_arthritis)
Thanks
If your data is in an object named infections, with attributes such as Septic_arthritis, the most straight-forward solution is to pass the data and the attribute as separate arguments, and then use getattr to get the data for the particular infection.
It would look something like this:
def escrito(data, infection):
write_window = Toplevel(root)
write_window.title(infection)
writing_box = tk.Text(write_window, font = ("calibri", 20), width = 60, height = 15, wrap="word")
writing_box.pack(expand = tk.YES, fill = tk.X)
writing_box.grid(row = 0, column = 0, sticky = 'nswe')
texto = '\n'.join(key + ":\n" + value for key, value in getattr(data, infection).items())
writing_box.insert("1.0", texto)
The important bit about the above code is that it uses getattr(data, infection) to get the data for the given infection.
If you want to create a button to call this function, it might look something like this:
button = tk.Button(..., command=lambda: escrito(infections, "Septic_arthritis"))
This will call the command escrito with two arguments: the object that contains all of the infections, and the key to the specific piece of information you want to display.
So the idea is making an encoder i mean when user write for example "a" in label called text the programme paste result for ex "}" and so on.
The question is do i have to write "if" for every letter in alphabet and every place in the label text i mean if user_code[0]
if user_code[1]
and so on
import tkinter as tk
#making main window
root = tk.Tk()
root.title("Szyfrator")
root.geometry("600x300")
#getting text
def getting_Text():
user_code = text.get("1.0",'end-1c')
if user_code[0] == 'a' :
result.insert(tk.END, '[', 'big')
if user_code[0] == 'b':
result.insert(tk.END, ';', 'big')
#UX of the window
right_margin = tk.Frame(root)
right_margin.pack (side=tk.RIGHT, expand =tk.YES , fill=tk.BOTH)
left_margin = tk.Frame(root)
left_margin.pack(side=tk.LEFT, expand=tk.YES, fill=tk.BOTH)
#after clicking button function getting_text() is used
button = tk.Button( root , text = "Szyfruj", activebackground = "#FFFFFF", command=getting_Text)
button.pack( side = tk.TOP )
text=tk.Text(root, width=36, height=15 )
text.pack(side= tk.LEFT)
result= tk.Text(root, width=36, height=15 )
result.pack(side=tk.RIGHT)
# ):
root.mainloop()
No, you can use a for-loop to iterate over the letters of user_code, and create a dictionary to map a letter to another.
encoded = {
"a": "[",
"b": ";"
}
def getting_Text():
user_code = text.get("1.0", 'end-1c')
for letter in user_code:
try:
result.insert(tk.END, encoded[letter], 'big')
except KeyError: # if we don't have an encoding for a letter, a KeyError will be raised which we capture
print("Oops, no encoding found for letter %s" % letter)
And if you have many different letter encodings and don't want to type in so much commas, quotes, colons, you can even create the dictionary like this:
letters = "abcdefghijklmnopqrstuvwxyz" # letters and encodings must have the same amount of symbols, else it may give you an IndexError: index out of range
encodings = "[;]:_-#'+*´`?=)(/&%$§!°^<>"
encoded = {key: value for key, value in zip(list(letters), list(encodings))}
I need your help to figure out how to make the following coding:
My idea is to get a message if fields name and quantity are in blank at the time I execute a function through a button. I printed what is the value if name and quantity are in blank and program says it is .!entry and .!entry2 respectively.
Unfortunately it doesn't work. What I am doing wrong?
if name == .!entry and quantity == .!entry2:
message = Label(root, text = 'Name and Quantity required' , fg = 'red')
message.grid(row = 4, column = 0, columnspan = 2, sticky = W + E)
return
As #JordyvanDongen pointed out in the comments you should use entry.get() to get the text inside the the entry object.
I suggest this for you code, assuming the entry objects are named name and quantity:
if not name.get() or not quantity.get():
message = Label(root, text = 'Both name and quantity are required', fg = 'red')
message.grid(row = 4, column = 0, columnspan = 2, sticky = W + E)
return None
I changed the conditional to or so that if either of the fields are blank it will be triggered but you may want to change it back to and depending on your purposes..
I am iterating through my dataframe, using each value in each column to add in popup. However width of popup is too small therefore one value is shown in multiple rows.
this is what my code looks like:
c = folium.Map(
location=[12.323, 146.029326],
zoom_start=14
)
for row in df.itertuples():
name = getattr(row, "name")
age = getattr(row, "age")
folium.Marker(
location = location,
popup=folium.Popup(f"""name= {name} <br>
age = {age} <br>
"""),
icon=plugins.BeautifyIcon(
border_color = color,
border_width = 2,
text_color = 'black'
)
).add_to(c)
I want enough space for each column value. How can I do this?
You can use the parameter max_width for the Popup object. You can specify a number that depends on the number of caracters in the line of the name like this :
popup=folium.Popup(f"""name= {name} <br>
age = {age} <br>
""", max_width=len(f"name= {name}")*20),
I'm trying to make a SVG file connected to a web scraper.
How do I change font and text size with svgwrite? I understand that I have to define a CSS style and somehow connect that to the text object. But how is this made?
Here's the code I have so far
import svgwrite
svg_document = svgwrite.Drawing(filename = "test-svgwrite3.svg",
size = ("1200px", "800px"))
#This is the line I'm stuck at
#svg_document.add(svg_document.style('style="font-family: Arial; font-size : 34;'))
svg_document.add(svg_document.rect(insert = (900, 800),
size = ("200px", "100px"),
stroke_width = "1",
stroke = "black",
fill = "rgb(255,255,0)"))
svg_document.add(svg_document.text("Reported Crimes in Sweden",
insert = (410, 50),
fill = "rgb(255,255,0)",
#This is the connection to the first line that I'm stuck at
#style = 'style="font-family: Arial; font-size : 104;'))
print(svg_document.tostring())
svg_document.save()
Manfred Moitzi the maker of SvgWrite mailed me an more eleborated answer;
This has to be done by CSS, use the 'class_' or 'style' keyword args to set text properties:
dwg = svgwrite.Drawing()
with 'style' keyword arg:
g = dwg.g(style="font-size:30;font-family:Comic Sans MS, Arial;font-weight:bold;font-
style:oblique;stroke:black;stroke-width:1;fill:none")
g.add(dwg.text("your text", insert=(10,30))) # settings are valid for all text added to 'g'
dwg.add(g)
with 'class_' keyword arg:
Create a CSS file with content:
.myclass {
font-size:30;
font-family:Comic Sans MS, Arial;
font-weight:bold;
font-style:oblique;
stroke:black;
stroke-width:1;
fill:none;
}
see CSS reference: http://www.w3schools.com/cssref/default.asp
dwg.add_stylesheet(filename, title="sometext") # same rules as for html files
g = dwg.g(class_="myclass")
g.add(dwg.text("your text", insert=(10,30))) # settings are valid for all text added to 'g'
dwg.add(g)
With 'class_' and 'style' keyword args you can style every graphic object and they can be used at container objects.
The answer was quite simple;
svg_document.add(svg_document.text("Reported Crimes in Sweden",
insert = (410, 50),
fill = "rgb(255,255,0)",
style = "font-size:10px; font-family:Arial"))
Set font-size like this:
dwg = svgwrite.Drawing('test.svg', profile='tiny')
dwg.add(dwg.text('Test',insert = (30, 55),font_size="10px",fill='black'))