Пример #1
0
#canvas.create_oval(cx, cy, cx+(r*2), cy+(r*2))
#canvas.create_oval(cx-(r*2), cy-(r*2), cx, cy)
#canvas.create_oval(cx, cy-(r*2), cx+(r*2), cy)

#canvas.mainloop()

## Úloha 2
#
# Nakresli olympíjske kruhy. Opýtaj sa používateľa na polomer kruhov a na
# súradnice prvého kruhu. pomocou výpočtov potom zisti súradnice všetkých
# ostatných kruhov. Všimni si, že kruhy sa na X-ovej osi nedotýkajú. Je tam
# istý offset. Offset nastav ako 2% z veľkosti polomeru.

import tkinter

canvas = tkinter.Canvas(width=640, height=480)
canvas.pack()

r = int(input("Zadaj polomer kruhu:"))
x = int(input("Zadaj suradnice x, y stredu prvého kruhu:"))
y = x

canvas.create_oval(x - r, y - r, x + r, y + r, width=3, outline="blue")
canvas.create_oval(x + 1.1 * r,
                   y - r,
                   x + 3.1 * r,
                   y + r,
                   width=3,
                   outline="black")
canvas.create_oval(x + 3.2 * r,
                   y - r,
Пример #2
0
import tkinter as tk
#create empty window
root = tk.Tk()
#window size
root.geometry("600x600")
#set title
root.title("Draw Face ")
#.....
canvas = tk.Canvas(root)
#eyes one
canvas.create_oval(110, 70, 210, 150, fill="blue")
canvas.create_oval(70, 70, 250, 150)
#eyes two
canvas.create_oval(400, 70, 500, 150, fill="blue")
canvas.create_oval(360, 70, 540, 150)
#nose
canvas.create_oval(270, 240, 300, 200, fill="red")
#mouth
canvas.create_rectangle(100, 350, 120, 420, fill="red", outline="red")
canvas.create_rectangle(500, 370, 480, 400, fill="red", outline="red")
canvas.create_rectangle(100, 400, 500, 420, fill="red", outline="red")
canvas.pack(expand=True, fill="both")
root.mainloop()


Пример #3
0
import tkinter as tk

cell_size = 20
board_size = 10  # ou 8 pour un échiquier
canvas_size = cell_size * board_size

colors = ["white", "black"]

root = tk.Tk()

canvas = tk.Canvas(root, width=canvas_size, height=canvas_size)
canvas.pack()

for x in range(board_size):
    for y in range(board_size):
        color = colors[(x + y) % 2]
        canvas.create_rectangle(
            y * cell_size,
            x * cell_size,
            y * cell_size + cell_size,
            x * cell_size + cell_size,
            fill=color, outline=color
        )

root.mainloop()
            name, desc, temp, pressure, humidity, wind_speed)
    except:
        final_str = 'There was a problem retrieving \ninformation'
    return final_str


def get_weather(entry):
    weather_key = '650d738f9c92b5791bd3405e1d6c92c7'
    url = 'https://api.openweathermap.org/data/2.5/weather'
    params = {'APPID': weather_key, 'q': entry, 'units': 'imperial'}
    response = requests.get(url, params=params, verify=False)
    weather = response.json()
    label['text'] = format_response(weather)


canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()

back_img = tk.PhotoImage(file='landscape3.png')

back_label = tk.Label(root, image=back_img)
back_label.place(relwidth=1, relheight=1)

frame = tk.Frame(root, bg='#80c1ff', bd=5)
frame.place(relx=0.5, rely=0.1, relwidth=0.65, relheight=0.1, anchor='n')

entry = tk.Entry(frame, font=('Courier', 20))
entry.place(relwidth=0.67, relheight=1)

button = tk.Button(frame,
                   text='Search',
from tkinter import *
import tkinter as tk
from tkinter import messagebox, simpledialog

window_width = 600
window_height = 600

root = tk.Tk()

canvas = tk.Canvas(root,
                   width=window_width,
                   height=window_height,
                   bg="#DDDDDD")
canvas.grid()

# 1. Ask the user what color tomato they would like and save their response
#    You can give them up to three choices
color = simpledialog.askstring('', 'red green or blue tomato?')

# 2. Use if-else statements to draw the tomato in the color that they chose
#    You can modify the code below or draw your own tomato
if color == 'red':
    canvas.create_oval(200, 200, 525, 450, fill="red", outline="")
elif color == 'green':
    canvas.create_oval(200, 200, 525, 450, fill="green", outline="")
elif color == 'blue':
    canvas.create_oval(200, 200, 525, 450, fill="blue", outline="")

canvas.create_rectangle(325, 100, 385, 230, fill="yellow", outline="")

root.mainloop()
Пример #6
0
            else:
                newPhrase = Phrase(row[0], row[1], row[2])
                phraseList.append(newPhrase)
root = Tk.Tk()
root.title("Picoh - Speech Database")
root.geometry('776x470')
operatingSystem = platform.system()
root.configure(bg='white')
root.resizable(0, 0)
root.protocol("WM_DELETE_WINDOW", on_closing)
##customFont = tkFont.Font(root, family="Letter Gothic Std", size=12)
if operatingSystem == "Darwin":
    customFont = tkFont.Font(family="Letter Gothic Std", size=11)
if operatingSystem == "Windows" or operatingSystem == "Linux":
    customFont = tkFont.Font(family="Helvetica", size=8)
canvasThree = Tk.Canvas(root)
canvas = Tk.Canvas(root)
canvasTwo = Tk.Canvas(root)
canvasSpacer = Tk.Canvas(root)
canvasTwo.config(width=750, height=75, bg='white')
canvasThree.config(width=750, height=25, bg='white')
# canvasTwo.geometry('200x150')
scroll_y = Tk.Scrollbar(root, orient="vertical", command=canvas.yview)
frame = Tk.Frame(canvas)
frameTwo = Tk.Frame(canvasTwo)
frameThree = Tk.Frame(canvasThree)
frame.bind_class("Text", "<Control-a>", selectall)
frameTwo.config(width=750, height=75, bg='white')
frameThree.config(width=750, height=25, bg='white')
# group of widgets
for phrase in phraseList:
Пример #7
0
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        global s
        global ifRefill
        global mission
        global stars
        global ib_status
        global bs_status
        global pp_status
        global es_status
        global anubis_status
        global task_id
        global task_timer
        global task_status
        global task_current_star
        global task_id_cycle

        def farmStarter():
            global stars
            global mission
            global ifRefill
            global current_task
            global ib_status
            global bs_status
            global pp_status
            global es_status
            global anubis_status
            global task_id
            global task_timer
            global task_status
            global task_current_star
            global task_id_cycle
            global task_timer_cycle
            global task_status_cycle
            while True:
                try:
                    get_mission_status()
                    task_init()
                    for counter in range(20):
                        if task_timer[
                                task_id_cycle[counter]] == 0 and task_status[
                                    task_id_cycle[counter]] == 'open':
                            pass
                        else:
                            if task_timer[task_id_cycle[counter]] != 0:
                                sleeper = int(
                                    task_timer[task_id_cycle[counter]])
                                time.sleep(sleeper)
                                mission_ender(
                                    task_id_cycle[counter],
                                    task_current_star[task_id_cycle[counter]])
                                break
                            elif task_timer[task_id_cycle[
                                    counter]] == 0 and task_status[
                                        task_id_cycle[counter]] == "progress":
                                mission_ender(
                                    task_id_cycle[counter],
                                    task_current_star[task_id_cycle[counter]])
                                break
                    while True:
                        get_mission_status()
                        task_init()
                        profile_json = s.get(
                            'https://wf.my.com/minigames/bp4/info/compose?methods=user.info'
                        ).json()
                        energy_count = int(profile_json['data']['user']['info']
                                           ['cheerfulness'])
                        if task_timer[mission] == 0 and task_status[
                                mission] == 'open':
                            if ifRefill:
                                if str(stars) == "3":
                                    if isAthlete():
                                        if energy_count < 10:
                                            energy_refill()
                                    else:
                                        if energy_count < 15:
                                            energy_refill()
                                elif str(stars) == "2":
                                    if isAthlete():
                                        if energy_count < 7:
                                            energy_refill()
                                    else:
                                        if energy_count < 12:
                                            energy_refill()
                                elif str(stars) == "1":
                                    if isAthlete():
                                        if energy_count < 3:
                                            energy_refill()
                                    else:
                                        if energy_count < 8:
                                            energy_refill()
                            mission_starter(mission, stars)
                        elif task_timer[mission] == 0 and task_status[
                                mission] == 'progress':
                            mission_ender(mission, stars)
                        time.sleep(5)
                except (KeyError, ValueError, TypeError,
                        requests.exceptions.ChunkedEncodingError,
                        json.decoder.JSONDecodeError,
                        requests.exceptions.ConnectionError,
                        requests.exceptions.ProxyError):
                    login(the_email, the_password)
                    continue
                break

        #set up canvas updater
        def canvasUpdater():
            while True:
                canvas.delete("all")
                reward_list = []
                reward_category = {}
                if os.path.isfile(
                        os.path.dirname(os.path.realpath(__file__)) + '/' +
                        username + '_log'):
                    log_session = open(
                        os.path.dirname(os.path.realpath(__file__)) + '/' +
                        username + '_log', "r")
                    log_content = log_session.readlines()
                    for i in range(len(log_content)):
                        log_content[i] = log_content[i].replace("'", "\"")
                        log_json = ast.literal_eval(log_content[i])
                        if log_json["data"]["result"] == "success":
                            reward_list.append(log_json['data']['rewards']
                                               ['reward']['item']['ext_name'])
                        else:
                            continue
                    for x in range(len(reward_list)):
                        if reward_list[x] not in reward_category:
                            reward_category.update({reward_list[x]: 1})
                        else:
                            reward_category.update({
                                reward_list[x]:
                                reward_category[reward_list[x]] + 1
                            })
                    reward_category_list = list(reward_category)
                    for y in range(len(reward_category)):
                        temp = (y + 1) * 20
                        canvas.create_text(
                            (20, temp),
                            text=reward_category_list[y] + ": " +
                            str(reward_category[reward_category_list[y]]),
                            anchor="w")
                else:
                    pass
                time.sleep(60)

        def mission_check(mission, stars):
            if stars == 1:
                difficulty = "1 star"
            elif stars == 2:
                difficulty = "2 stars"
            elif stars == 3:
                difficulty = "3 stars"
            mission_label = tk.Label(self,
                                     text=mission + ", " + difficulty,
                                     font=("San Francisco", 18))
            mission_label.grid(row=1, sticky="E", columnspan=2, padx=20)

        #function to check if the program is actively farming
        def status_check():
            while True:
                try:
                    if farm_process.is_alive():
                        status_label = tk.Label(self,
                                                text="Status: active",
                                                font=("San Francisco", 18))
                        status_label.grid(row=1,
                                          sticky="W",
                                          columnspan=2,
                                          padx=20)
                    else:
                        status_label = tk.Label(self,
                                                text="Status: inactive",
                                                font=("San Francisco", 18))
                        status_label.grid(row=1,
                                          sticky="W",
                                          columnspan=2,
                                          padx=20)
                    time.sleep(1)
                except:
                    continue

        farm_process = multiprocessing.Process(target=farmStarter)
        farm_process.start()
        status_check_process = threading._start_new_thread(status_check, ())

        def goodbye():
            farm_process.terminate()
            exit()

        def reconfig():
            farm_process.terminate()
            master.switch_frame(config_page)

        #init the thread for mission check
        mission_thread = threading._start_new_thread(mission_check,
                                                     (mission, stars))
        #set up the label
        the_label = tk.Label(self,
                             text="Dashboard",
                             font=("San Francisco", 20))
        the_label.grid(row=0, columnspan=2)
        reward_label = tk.Label(self,
                                text="Rewards:",
                                font=("San Francisco", 16))
        reward_label.grid(row=2, column=0, sticky="W", padx=10)
        #set up a canvas
        canvas = tk.Canvas(self)
        canvas.grid(row=3, column=0)
        canvas_thread = threading._start_new_thread(canvasUpdater, ())
        #set up buttons
        start_button = tk.Button(self,
                                 text="Reconfigure",
                                 command=lambda: reconfig(),
                                 width=9)
        start_button.grid(row=3, column=1, sticky="N", padx=10, pady=50)
        stop_button = tk.Button(self,
                                text="Stop",
                                command=lambda: goodbye(),
                                width=9)
        stop_button.grid(row=3, column=1, padx=10, pady=50)
Пример #8
0
    def __init__(self, master, _winheight, _winwidth):

        #获取本地音乐文件
        self.extensionlist = ['mp3', 'flac']
        self.musiclist = []
        for extension in self.extensionlist:
            file_list = glob.glob('music/*.' + extension)  #返回一个列表
            for item in file_list:
                self.musiclist.append(item[6:])

        #尺寸变量
        self.winheight = _winheight
        self.winwidth = _winwidth
        self.photopadding = self.winwidth / 128
        self.photoleftpadding = 500
        self.photowidth = self.winwidth - self.photopadding * 2 - self.photoleftpadding
        self.photoheight = 70
        self.photomovex = (self.winwidth - self.photowidth) / 2
        self.master = master
        self.musicreadlist = []
        self.topheight = 130  #顶部标题高度
        self.backbtnheight = self.topheight / 2
        self.backbtnwidth = self.backbtnheight
        self.backbtnpadding = self.topheight / 4  #顶部按钮的间距
        self.pausebtnwidth = 40
        self.pausebtnmovey = (self.photoheight - self.pausebtnwidth) / 2
        self.pausebtnmovex = self.photowidth - 30 - self.pausebtnwidth
        self.curid = -1
        self.pausemusicflag = False  #是否有音乐暂停
        self.pausemusicid = -1  #暂停的音乐id
        #读取图片
        self.backimg = ImageTk.PhotoImage(
            Image.open("srcimage/toleft.jpg").resize(
                (int(self.backbtnwidth), int(self.backbtnheight))))
        self.pauseimg = ImageTk.PhotoImage(
            Image.open("srcimage/pause.jpg").resize(
                (int(self.pausebtnwidth), int(self.pausebtnwidth))))
        self.playimg = ImageTk.PhotoImage(
            Image.open("srcimage/play.jpg").resize(
                (int(self.pausebtnwidth), int(self.pausebtnwidth))))
        self.musicpage = tk.Canvas(self.master,
                                   bg="pink",
                                   width=self.winwidth,
                                   height=self.winheight)
        self.musicpage.place(x=0, y=0)
        self.musicpage.configure(highlightthickness=0)
        #背景
        bg = background(self.musicpage, self.winheight, self.winwidth, "call")
        #返回按钮
        backbtn(self.musicpage, self.winheight, self.winwidth)
        #标题
        title(self.musicpage, self.winheight, self.winwidth, "播放音乐")
        self.Canvaslist = []
        self.pausebtnlist = []
        #图片缩略图放置
        for n in range(0, len(self.musiclist)):
            self.Canvaslist.append(
                tk.Canvas(self.musicpage,
                          bg="white",
                          width=int(self.photowidth),
                          height=int(self.photoheight)))
            self.Canvaslist[n].place(
                x=self.photomovex,
                y=n * (self.photoheight + self.photopadding) + self.topheight)
            self.Canvaslist[n].create_text(self.photowidth / 2,
                                           self.photoheight / 2,
                                           text=self.musiclist[n],
                                           font=("黑体", 25))
            self.pausebtnlist.append(
                tk.Button(self.Canvaslist[n],
                          image=self.playimg,
                          width=self.pausebtnwidth,
                          height=self.pausebtnwidth,
                          command=self.returnfun(n)))
            self.pausebtnlist[n].place(x=self.pausebtnmovex,
                                       y=self.pausebtnmovey)
        bg.showimage()
Пример #9
0
                                          title="Select File",
                                          filetypes=(("executables", "*.exe"),
                                                     ("all files", "*.*")))
    apps.append(filename)
    print(filename)
    for app in apps:
        label = tk.Label(frame, text=app, bg="gray")
        label.pack()


def runApps():
    for app in apps:
        os.startfile(app)


canvas = tk.Canvas(root, height=500, width=500, bg="#263D42")
canvas.pack()
frame = tk.Frame(root, bg="white")
frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1)
openFile = tk.Button(root,
                     text="Open File",
                     padx=15,
                     pady=10,
                     fg="white",
                     bg="maroon",
                     command=addApp)
openFile.pack()
runApps = tk.Button(root,
                    text="Run Apps",
                    padx=15,
                    pady=10,
Пример #10
0
generate_button = ttk.Button(frame,
                             text="Generate Random",
                             command=lambda: generate())
frame.grid_propagate(False)
frame.rowconfigure(0, weight=2)
frame.grid(row=0, column=0)
generate_button.grid(sticky="ens")

width = 3
number = int((screen_width - 2) / width)
rect_list = []
height_list = []
button_list = [0 for i in range(3)]
#number =5
"""Creating the pane that will contain all the rectangles with different heights"""
rectangle_pane = tk.Canvas(screen, width=screen_width, height=screen_width)
rectangle_pane.grid(row=1, column=0)
rectangle_pane.config(background='#b5e1f5')
"""Creating Frame that will hold the sort buttons"""
sort_frame = tk.Frame(screen, width=screen_width, height=50)
sort_frame.grid_propagate(False)
sort_frame.rowconfigure(0, weight=2)
sort_frame.grid(row=2, column=0)
"""creating the button that will bubble sort the list"""
button_list[0] = ttk.Button(sort_frame,
                            text="Bubble sort",
                            command=lambda: sort(0))
button_list[0].config(state="disabled")
button_list[0].grid(row=0, column=0)
""""Creating the button that will use selection sort"""
button_list[1] = ttk.Button(sort_frame,
Пример #11
0
            self.dico[idd][0] -= 1
            if self.dico[idd][0] == -1:
                #print("last", self.dico)
                self.delete(idd)


def main_loop():

    highlight.find()

    root.after(50, main_loop)


if __name__ == "__main__":
    root = tk.Tk()
    cav = tk.Canvas(root,
                    width=1200,
                    height=675,
                    bg="black",
                    highlightthickness=0)
    cav.pack()

    highlight = Highlight(cav)

    highlight.create_text(500, 300, "Bonjour", "white", "Arial", 20)
    highlight.create_text(500, 350, "Salut", "white", "Arial", 20)

    main_loop()

    root.mainloop()
Пример #12
0
def sandbox_mode(root, mqtt):
    """A free-for-all mode where the user is completely free to control the
    robot"""
    root.destroy()
    sb_root = tkinter.Tk()
    sb_root.title("King-Kong: Sandbox mode")
    sb_frame = ttk.Frame(sb_root, padding=30)
    sb_frame.grid()

    return_button = ttk.Button(sb_frame, text="Return")
    return_button.grid(row=0, column=2)
    return_button['command'] = lambda: quit_mode(mqtt, sb_root)
    left_blank_space = ttk.Label(sb_frame, text="           ", padding=20)
    left_blank_space.grid(row=0, column=0)

    sb_intro = ttk.Label(sb_frame,
                         text="Welcome to sandbox mode!",
                         font="Calibri")
    sb_intro.grid(row=1, column=1)
    sb_intro1 = ttk.Label(sb_frame,
                          text="In this mode, you can control the "
                          "robot in any way you want!")
    sb_intro1.grid(row=2, column=1)
    sb_intro2 = ttk.Label(sb_frame,
                          text="Nothing's stopping you from going "
                          "on a rampage with robo King-Kong.")
    sb_intro2.grid(row=3, column=1)
    sb_intro3 = ttk.Label(sb_frame,
                          text="First you might need a few "
                          "directions for how to use robo "
                          "King-Kong...")
    sb_intro3.grid(row=4, column=1)

    sb_direc = ttk.Label(sb_frame, text="How to use the robot:")
    sb_direc.grid(row=5, column=1)
    sb_movedirec = ttk.Label(sb_frame,
                             text="Use the arrow keys to move the "
                             "robot around",
                             padding=5)
    sb_movedirec.grid(row=6, column=1)
    sb_armdirec = ttk.Label(sb_frame,
                            text="Press the 'u' and 'd' buttons "
                            "the move the robots arm")
    sb_armdirec.grid(row=7, column=1)
    sb_stopdirec = ttk.Label(sb_frame,
                             text="Press the space bar between "
                             "actions to stop the robot",
                             padding=5)
    sb_stopdirec.grid(row=8, column=1)

    sb_root.bind('<Up>', lambda event: move_forward(mqtt))
    sb_root.bind('<Down>', lambda event: move_backward(mqtt))
    sb_root.bind('<Left>', lambda event: move_left(mqtt))
    sb_root.bind('<Right>', lambda event: move_right(mqtt))
    sb_root.bind('<space>', lambda event: stop(mqtt))
    sb_root.bind('<u>', lambda event: arm_up(mqtt))
    sb_root.bind('<d>', lambda event: arm_down(mqtt))

    sb_noisedirec = ttk.Label(sb_frame,
                              text="Use the buttons below to make "
                              "robo King-Kong speak!")
    sb_panel = tkinter.Canvas(sb_root)
    sb_panel.grid()
    sb_noisedirec.grid(row=9, column=1)
    noise_button = ttk.Button(sb_panel, text="Noises")
    noise_button.grid(row=10, column=0)
    noise_button['command'] = lambda: make_noise(mqtt)
    quote_button = ttk.Button(sb_panel, text="King-Kong Joke")
    quote_button.grid(row=10, column=2)
    quote_button['command'] = lambda: joke(mqtt)

    btm_blank_space = ttk.Label(sb_panel, text="           ", padding=20)
    btm_blank_space.grid(row=11, column=0)

    sb_root.mainloop()
import tkinter as tk
import time
import math
from random import randrange as rnd, choice
import itertools


root = tk.Tk()
fr = tk.Frame(root)
root.geometry('900x600')
canv = tk.Canvas(root, bg='white')
canv.pack(fill=tk.BOTH, expand=1)


class ball():
    def __init__(self):
        self.x = 30
        self.y = 400
        self.r = 10
        self.vx = 0
        self.vy = 0
        self.hit = 0
        self.color = choice(['blue', 'green', 'red', 'orange', 'grey'])
        self.id = canv.create_oval(
                self.x - self.r,
                self.y - self.r,
                self.x + self.r,
                self.y + self.r,
                fill=self.color
        )
Пример #14
0
    global listCircle, circleToPop
    for i in range(len(listCircle)):
        circle = listCircle[i]
        y = canvas.coords(circle)[1]
        if y < 600:
            canvas.move(circle, 0, 10)
        else:
            circleToPop.append(i)
            canvas.delete(circle)
    for index in sorted(circleToPop, reverse=True):
        listCircle.pop(index)
    circleToPop = []
    canvas.after(50, lambda: moveCircles())


SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
SCREEN_TITLE = "PNC Shoot'em up game in Python"

root = tk.Tk()
root.geometry(str(SCREEN_WIDTH) + "x" + str(SCREEN_HEIGHT))
frame = tk.Frame()
frame.master.title("Shoot'em up in TK")
frame.pack(expand=True, fill='both')
canvas = tk.Canvas(frame)
canvas.pack(expand=True, fill='both')

moveCircles()  #I run the qnimqtion of circles

root.bind("<space>", createCircle)
root.mainloop()
Пример #15
0
def feedbackShow_action(feed, tkvar):
    mydb = pymysql.connect(host="localhost",
                           user="******",
                           passwd="",
                           database="project")

    mycursor = mydb.cursor()

    def on_configure(event):
        # update scrollregion after starting 'mainloop'
        # when all widgets are in canvas
        canvas.configure(scrollregion=canvas.bbox('all'))

    # --- create canvas with scrollbar ---

    canvas = tk.Canvas(feed)
    canvas.pack(fill=BOTH, expand=True, side=tk.LEFT)

    scrollbar = tk.Scrollbar(feed, command=canvas.yview)
    scrollbar.pack(side=tk.RIGHT, fill='y')

    canvas.configure(yscrollcommand=scrollbar.set)

    # update scrollregion after starting 'mainloop'
    # when all widgets are in canvas
    canvas.bind('<Configure>', on_configure)

    # --- put frame in canvas ---

    frame = tk.Frame(canvas)
    canvas.create_window((0, 0), window=frame, anchor='nw')
    if tkvar == 'electrical':
        mycursor.execute("SELECT * FROM feedback_electrical")
        obj = mycursor.fetchall()

        row_count = len(obj)
        i = 0
        Label(frame,
              text='FEEDBACK VIEW WINDOW of Electrical Department',
              font=('Candara Bold Italic', 16)).pack(side=TOP, pady=10)
        while i < row_count:
            pr = ('NAME:', obj[i][0])
            Label(frame, text=pr, font=('Calibri', 13)).pack(side=TOP, pady=10)
            pr = ('FEEDBACK:', obj[i][1])
            Label(frame, text=pr, font=('Calibri', 13)).pack(side=TOP, pady=10)
            pr = ('LOCATION:', obj[i][2])
            Label(frame, text=pr, font=('Calibri', 13)).pack(side=TOP, pady=10)
            pr = ('PHONE_NO.:', obj[i][3])
            Label(frame, text=pr, font=('Calibri', 13)).pack(side=TOP, pady=10)
            pr = ('---------------------------------------------------')
            Label(frame, text=pr, font=('Calibri', 13)).pack(side=TOP, pady=10)
            i = i + 1
    elif tkvar.get() == 'sports' or tkvar.get() == 'seminar' or tkvar.get(
    ) == 'tech-fest':
        quere = "SELECT * FROM `feedback_electrical_" + tkvar.get() + "`"
        mycursor.execute(quere)
        obj = mycursor.fetchall()

        row_count = len(obj)
        i = 0
        Label(frame,
              text='FEEDBACK VIEW WINDOW of ' + tkvar.get(),
              font=('Candara Bold Italic', 16)).pack(side=TOP, pady=10)
        while i < row_count:
            pr = ('NAME:', obj[i][0])
            Label(frame, text=pr, font=('Calibri', 13)).pack(side=TOP, pady=10)
            pr = ('FEEDBACK:', obj[i][1])
            Label(frame, text=pr, font=('Calibri', 13)).pack(side=TOP, pady=10)
            pr = ('LOCATION:', obj[i][2])
            Label(frame, text=pr, font=('Calibri', 13)).pack(side=TOP, pady=10)
            pr = ('PHONE_NO.:', obj[i][3])
            Label(frame, text=pr, font=('Calibri', 13)).pack(side=TOP, pady=10)
            pr = ('---------------------------------------------------')
            Label(frame, text=pr, font=('Calibri', 13)).pack(side=TOP, pady=10)
            i = i + 1
 def add_frame(self, **kwargs):
     if kwargs['id'] in self.containers.keys():
         self.containers[kwargs['id']].destroy()
         garbage = self.containers.pop(kwargs['id'])
         del garbage
     kwargs['owner'] = self.owner
     kwargs['type'] = 'frame'
     if kwargs['scroll']['horizontal'] or kwargs['scroll']['vertical']:
         canvas = None
         scroll_barx = None
         scroll_bary = None
         canvas = tk.Canvas(self, bg='white')
         kwargs['master'] = canvas
         self.containers[kwargs['id']] = MyPyWindow(**kwargs)
         self.containers[kwargs['id']].setup()
         canvas.create_window((0, 0),
                              window=self.containers[kwargs['id']],
                              anchor='nw')
         if kwargs['scroll']['horizontal']:
             scroll_barx = tk.Scrollbar(self,
                                        orient='horizontal',
                                        command=canvas.xview)
             canvas.configure(xscrollcommand=scroll_barx.set)
         if kwargs['scroll']['vertical']:
             scroll_bary = tk.Scrollbar(self,
                                        orient='vertical',
                                        command=canvas.yview)
             canvas.configure(yscrollcommand=scroll_bary.set)
         self.containers[kwargs['id']].bind(
             '<Configure>',
             lambda event, _canvas=canvas: self.scroller(_canvas))
         if kwargs['scroll']['horizontal'] and kwargs['scroll']['vertical']:
             kwargs['scroll_window_size']['rowspan'] -= 20
             kwargs['scroll_window_size']['columnspan'] -= 20
             scroll_barx.grid(
                 row=kwargs['scroll_window_size']['row'] +
                 kwargs['scroll_window_size']['rowspan'],
                 rowspan=20,
                 column=kwargs['scroll_window_size']['column'],
                 columnspan=kwargs['scroll_window_size']['columnspan'],
                 sticky='NWE')
             scroll_bary.grid(
                 row=kwargs['scroll_window_size']['row'],
                 rowspan=kwargs['scroll_window_size']['rowspan'],
                 column=kwargs['scroll_window_size']['column'] +
                 kwargs['scroll_window_size']['columnspan'],
                 columnspan=20,
                 sticky='NSW')
         elif kwargs['scroll']['horizontal']:
             kwargs['scroll_window_size']['rowspan'] -= 20
             scroll_barx.grid(
                 row=kwargs['scroll_window_size']['row'] +
                 kwargs['scroll_window_size']['rowspan'],
                 rowspan=20,
                 column=kwargs['scroll_window_size']['column'],
                 columnspan=kwargs['scroll_window_size']['columnspan'],
                 sticky='NWE')
         elif kwargs['scroll']['vertical']:
             kwargs['scroll_window_size']['columnspan'] -= 20
             scroll_bary.grid(
                 row=kwargs['scroll_window_size']['row'],
                 rowspan=kwargs['scroll_window_size']['rowspan'],
                 column=kwargs['scroll_window_size']['column'] +
                 kwargs['scroll_window_size']['columnspan'],
                 columnspan=20,
                 sticky='NSW')
         canvas.grid(**kwargs['scroll_window_size'])
     else:
         kwargs['master'] = self
         self.containers[kwargs['id']] = MyPyWindow(**kwargs)
         self.containers[kwargs['id']].setup()
         self.containers[kwargs['id']].configure({'bg': 'green'})
     self.containers[kwargs['id']].dragger = self.containers[kwargs['id']]
Пример #17
0
mouse_text = tk.StringVar()
mouse_entry = tk.Entry(info_frame, textvariable=mouse_text, width=25)
mouse_entry.grid(row=0, column=0)

input_label = tk.Label(info_frame, text="              Text Input:")
input_label.grid(row=0, column=1)

input_text = tk.StringVar()
input_entry = tk.Entry(info_frame, textvariable=input_text, width=15)
input_entry.grid(row=0, column=2)

canvas_frame = tk.Frame(window, bd=2, highlightbackground="black")
canvas_frame.grid(row=2, column=0, columnspan=2, sticky=tk.W)

canvas = tk.Canvas(canvas_frame, width=500, height=300, highlightbackground="white")
canvas.pack()

canvas.bind("<Button-1>", mouseLDown)
canvas.bind("<Motion>", mouseMove)
canvas.bind("<ButtonRelease-1>", mouseLUp)

list_frame = tk.Frame(window)
list_frame.grid(row=0, rowspan=3, column=2)

list_box = tk.Listbox(list_frame, width=20, height=20)
list_box.grid(row=0, column=0, columnspan=3)

width_plus_button = tk.Button(list_frame, text="+", width=4, command=widthPlusButton)
width_plus_button.grid(row=1, column=0)
Пример #18
0
# button2.pack(side='left')
# button3.pack(side='left')

# mainWindow.mainloop()

mainWindow = tkinter.Tk()
mainWindow.title("Hello world")
mainWindow.geometry('640x480-8-200')

label = tkinter.Label(mainWindow, text="Hello World")
label.grid(row=0, column=0)

leftFrame = tkinter.Frame(mainWindow)
leftFrame.grid(row=1, column=1)

canvas = tkinter.Canvas(leftFrame, relief='raised', borderwidth=1)
canvas.grid(row=1, column=0)

rightFrame = tkinter.Frame(mainWindow)
rightFrame.grid(row=1, column=2, sticky='n')

button1 = tkinter.Button(rightFrame, text="Open")
button2 = tkinter.Button(rightFrame, text="Edit")
button3 = tkinter.Button(rightFrame, text="Close")
button1.grid(row=0, column=0)
button2.grid(row=1, column=0)
button3.grid(row=2, column=0)

mainWindow.columnconfigure(0, weight=1)
mainWindow.columnconfigure(1, weight=1)
mainWindow.grid_columnconfigure(2, weight=1)
Пример #19
0
                         text="Cost: %d" % MED_Matrix[-1][-1],
                         fg='blue',
                         font=('Arial', 20, 'bold'))
    canvas1.create_window(200, 160, window=Score_Med)

    #show table via med matrix
    btn_ShowTable = tk.Button(text='Show Table',
                              command=lambda: Show_MED_table(MED_Matrix),
                              font=('Arial', 9, 'bold'))
    canvas1.create_window(200, 200, window=btn_ShowTable)


root = tk.Tk()
root.title("Minimun Edit Distance")
#create a canvas window
canvas1 = tk.Canvas(root, width=400, height=300)
canvas1.pack()

#create labels
source_label = tk.Label(root, text="Source")
canvas1.create_window(100, 60, window=source_label)
target_label = tk.Label(root, text="Target")
canvas1.create_window(300, 60, window=target_label)

#create textbox --> get input
source_input = tk.Entry(root)
canvas1.create_window(100, 80, window=source_input)

target_input = tk.Entry(root)
canvas1.create_window(300, 80, window=target_input)
Пример #20
0
            snake.append(
                canvas.create_rectangle(25 * matrix_x + (25 * size_snake),
                                        matrix_y * 25,
                                        25 + 25 * matrix_x + (25 * size_snake),
                                        matrix_y * 25 + 25,
                                        outline='red'))
        elif orientation_memory == 3:
            snake.append(
                canvas.create_rectangle(25 * matrix_x,
                                        matrix_y * 25 + (25 * size_snake),
                                        25 * matrix_x + 25,
                                        matrix_y * 25 + (25 * size_snake) + 25,
                                        outline='red'))


window = tk.Tk()
canvas = tk.Canvas(window, width=1000, height=700, bg='black')
canvas.pack()
snake.append(canvas.create_rectangle(25, 0, 50, 25, outline='red'))
snake.append(canvas.create_rectangle(0, 0, 25, 25, outline='red'))

fruit_draw = canvas.create_rectangle(25 * fruit_pos[0],
                                     (25 + 25 * fruit_pos[1]),
                                     (25 + 25 * fruit_pos[0]),
                                     25 * fruit_pos[1],
                                     outline='yellow')

canvas.bind_all("<KeyPress>", key_pressed)
#automove()
canvas.mainloop()
Пример #21
0
    showInstructions = False
    goodGraphics = True
    forget = True
button = Button(leftPane, text="Old Grapics", command=startGame)
button2 = Button(leftPane, text="New Graphics", command=startGame2)
while showInstructions == True:
    leftPane.pack()
    instructions.pack()
    button.pack(side=RIGHT)
    button2.pack(side=LEFT)
    main_window.update()
if forget == True:
    button.pack_forget()
    button2.pack_forget()
    leftPane.pack_forget()
c = tkinter.Canvas(main_window, width=1350, height=550, bg="white") 
c.pack(side=LEFT)
instructions.pack_forget()
scoreChangeList = [[400,25],[800,20],[1200,15],[1600,12],[2000,10],[3000,9],[4000,8],[5000,7],[6000,6],[7000,5],[10000,3]]
leftPane = Frame(main_window,width=400,height=550,bg="grey")
leftPane.pack(side=RIGHT)
title = Label(leftPane,text=("\nTetris\n"),font=("Agency FB Bold",52),bg="grey")
title.pack(side=TOP)
speedLabel = Label(leftPane,text="Speed: " + str(12 - (len(scoreChangeList))),font=("Agency FB Bold",20),bg="Grey")
shapeIcons = ["####\n","###\n    #","    ###\n#","##\n##","   ##\n## ","###\n # ","##\n    ## "] 
shapesList = [  [[[3,1],[4,1],[5,1],[6,1]],[1]]  ,[[[5,2],[3,1],[4,1],[5,1]],[2]],[[[3,2],[3,1],[4,1],[5,1]],[3]]  ,  [[[4,2],[3,2],[3,1],[4,1],],[4]] , [[[5,2],[4,2],[5,1],[6,1]],[5]] , [[[4,2],[3,1],[4,1],[5,1]],[6]] ,  [[[5,2],[6,2],[4,1],[5,1]],[7]]]
nextShapeToSpawn = random.choice(shapesList)
score = Label(leftPane,text="Score: " + str(playerScore) + ("\n\nNext Shape\n\n") + (shapeIcons[(nextShapeToSpawn[1][0])-1]),font=("Agency FB Bold",20),bg="Grey")
score2 = Label(leftPane,text="Hi-Score: " + str(hiScore) + ("\n"),font=("Agency FB Bold",20),bg="Grey")
score2.pack(side=TOP)
speedLabel.pack(side=TOP)
Пример #22
0
# coding:utf-8
import tkinter as tk

def click(event):
    # クリックされたときにそこに描画する
    canvas.create_oval(event.x - 20,
                       event.y - 20,
                       event.x + 20,
                       event.y + 20,
                       fill="red",
                       width=0)

# ウィンドウを描く
root = tk.Tk()
root.geometry("600x400")
# キャンバスを置く
canvas = tk.Canvas(root, width=600, height=400, bg="white")
canvas.place(x=0, y=0)
# イベントを設定する
canvas.bind("<Button-1>", click)
root.mainloop()

Пример #23
0
#Filip Jenis, septima B
import tkinter
canvas = tkinter.Canvas()
canvas.pack()
canvas.create_line(10, 10, 210, 200, width=50, fill="blue")
canvas.create_line(10, 10, 210, 200, width=40, fill="yellow")
canvas.create_line(10, 10, 210, 200, width=30, fill="green")
canvas.create_line(10, 10, 210, 200, width=22, fill="black")
canvas.create_line(10, 10, 210, 200, width=20, fill="blue")
canvas.create_line(10, 10, 210, 200, width=10, fill="white")
canvas.create_line(10, 10, 210, 200, width=7, fill="black")
Пример #24
0
def main():
    global flip_timer

    # --- Inner Functions ---
    # Known Answer
    def rightWord():
        global known_words
        current_word = randomWord()
        known_words += current_word
        unknown_words.remove(current_word)
        words_to_learn = pd.DataFrame(unknown_words)
        words_to_learn.to_csv(DATA_UNLEARNED, index=False)

    # Next card
    def randomWord():
        global flip_timer, unknown_words, showed_words
        window.after_cancel(flip_timer)
        # Variables
        current_card = choice(unknown_words)
        while current_card in showed_words:
            current_card = choice(unknown_words)
        showed_words += current_card
        language = "French"
        word = current_card[language]
        new_color = "black"

        # Configs
        canvas.itemconfig(canvas_image, image=front_card_img)
        canvas.itemconfig(lb_language, text=language, fill=new_color)
        canvas.itemconfig(lb_word, text=word, fill=new_color)

        # Flip the card after 3 sec
        flip_timer = window.after(5000, flipCard, current_card)
        return current_card

    # Flip card
    def flipCard(current_card: dict):
        new_language = "English"
        new_color = "white"
        canvas.itemconfig(canvas_image, image=back_card_img)
        canvas.itemconfig(lb_language, text=new_language, fill=new_color)
        canvas.itemconfig(lb_word, text=current_card[new_language], fill=new_color)

    # --- UI Setup ---
    # Window
    window = tk.Tk()
    window.title(WINDOW_TITLE)
    window.config(bg=BACKGROUND_COLOR, padx=WINDOW_PAD_X, pady=WINDOW_PAD_Y)

    # Images
    front_card_img = tk.PhotoImage(file="./images/card_front.png")
    back_card_img = tk.PhotoImage(file="./images/card_back.png")
    right_img = tk.PhotoImage(file="./images/right.png")
    wrong_img = tk.PhotoImage(file="./images/wrong.png")

    # Cards
    canvas = tk.Canvas(width=800, height=526)
    canvas_image = canvas.create_image(400, 263, image=front_card_img)
    canvas.config(bg=BACKGROUND_COLOR, highlightthickness=0)
    canvas.grid(row=0, column=0, columnspan=2)

    # Words
    lb_language = canvas.create_text(
        LB_LANG_X, LB_LANG_Y,
        font=(
            LB_LANG_FONT,
            LB_LANG_FONT_SIZE,
            LB_LANG_FONT_STYLE
        )
    )

    lb_word = canvas.create_text(
        LB_WORD_X, LB_WORD_Y,
        font=(
            LB_WORD_FONT,
            LB_WORD_FONT_SIZE,
            LB_WORD_FONT_STYLE
        )
    )

    # Buttons
    btn_right = tk.Button(image=right_img, highlightthickness=0, command=rightWord)
    btn_right.grid(row=1, column=1)

    btn_wrong = tk.Button(image=wrong_img, highlightthickness=0, command=randomWord)
    btn_wrong.grid(row=1, column=0)

    # Initial state
    flip_timer = window.after(0, randomWord)

    # --- MAINLOOP ---
    window.mainloop()
Пример #25
0
        settings.SCREEN_SIZE[1] // 2 - settings.WINDOW_SIZE[1] // 2))
    tk_root.config(bg="black")
    tk_canvas.configure(bd=0, highlightthickness=0)

    tk_root.protocol('WM_DELETE_WINDOW', exit_app)  # root is your root window


def exit_app():
    # check if saving
    # if not:
    tk_root.destroy()


if __name__ == "__main__":
    tk_root = tk.Tk()
    tk_canvas = tk.Canvas(tk_root)

    img = ImageTk.PhotoImage(file=settings.SRC_DIR + '/icons/mindmap.png')
    tk_root.tk.call('wm', 'iconphoto', tk_root._w, img)

    graphics_init()

    filename = settings.SRC_DIR + "/Sheets/tmp_thought.json"
    if len(sys.argv) >= 2:
        filename = sys.argv[1]

    print("filename:", filename)

    sheet = Sheet(root=tk_root, canvas=tk_canvas, filename=filename)

    # have to do this after creating sheet, since resizeLayout calls sheet resize functions
Пример #26
0
def show(params):
  window = tkinter.Tk()

  image_filename = os.path.join(os.path.dirname(__file__), "%s.png" % params.cost_func.__name__)
  image  = tkinter.PhotoImage(file = image_filename)
  width  = image.width ()
  height = image.height()
  
  algo = metaheuristic_optimizer.artificial_bee_colony.Algorithm(params.cost_func, params.nb_dimension, params.min_x, params.max_x)
  
  def iterate():
    algo.iterate()
    print(algo.nb_cost_computed, "tested positions, best result:", algo.get_lowest_cost())
    
  canvas_items = []
  def update():
    nonlocal canvas_items
    for item in canvas_items: canvas.delete(item)
    canvas_items = []
    for mode, pos1, pos2 in algo.last_moves:
      x1 = width  * (pos1[0] - params.min_x) / (params.max_x - params.min_x)
      y1 = height * (pos1[1] - params.min_x) / (params.max_x - params.min_x)
      x2 = width  * (pos2[0] - params.min_x) / (params.max_x - params.min_x)
      y2 = height * (pos2[1] - params.min_x) / (params.max_x - params.min_x)
      if   mode == 1: color = "green"
      elif mode == 2: color = "blue"
      elif mode == 3: color = "red"
      else:           color = "cyan"
      canvas_items.append(canvas.create_line(x1, y1, x2, y2, fill = color))
      canvas_items.append(canvas.create_rectangle(x2 - 1, y2 - 1, x2 + 1, y2 + 1, outline = color, fill = color))
      
  def run_1_gen():
    iterate()
    update()
    
  def run_100_gen():
    for i in range(100): iterate()
    update()
    
  looping = False
  def loop():
    nonlocal looping
    looping = not looping
    if looping: loop_iteration()
    
  def loop_iteration():
    iterate()
    update()
    
    if looping: canvas.after(100, loop_iteration)
    
  stop_clicked = True
  def stop_loop(): stop_clicked = True
  
  def reset():
    algo.reset()
    update()
  
  frame  = tkinter.Frame(window)
  frame.pack()
  
  canvas = tkinter.Canvas(frame, bg = "white", width = width, height = height)
  canvas.pack()
  canvas.create_image(width / 2, height / 2, image = image)
  
  button = tkinter.Button(frame, text = "Run 1   iteration" , command = run_1_gen)
  button.pack()
  
  button = tkinter.Button(frame, text = "Run 100 iterations" , command = run_100_gen)
  button.pack()
  
  button = tkinter.Button(frame, text = "Loop" , command = loop)
  button.pack()
  
  button = tkinter.Button(frame, text = "Reset" , command = reset)
  button.pack()
  
    
  update()
    
  window.mainloop()
Пример #27
0
        topmessage.insert(
            'insert',
            f'Your hand has a value of {p1_value} and the dealer has a hand of {dealer_value}. Dealer wins!\n'
        )
    else:
        topmessage.insert(
            'insert',
            f'Your hand has a value of {p1_value} and the dealer has a hand of {dealer_value}. Its a tie!\n'
        )
    play_again()
    return


root = tk.Tk()

canvas = tk.Canvas(root, height=height, width=width)
canvas.pack()
background_image = tk.PhotoImage(file='playingcards.png')
background_label = tk.Label(root, image=background_image)
background_label.place(relwidth=1, relheight=1)
topframe = tk.Frame(root, bg='black', bd=5)
topframe.place(relx=.1, rely=.1, relheight=.5, relwidth=.8)
topmessage = tk.Text(topframe, width='5', wrap='word')
topmessage.place(relheight=1, relwidth=1)
scrollbar = tk.Scrollbar(topmessage, command=topmessage.yview)
scrollbar.place(relx=0.99, relheight=1, relwidth=0)
topmessage['yscrollcommand'] = scrollbar.set(0, 0)
bottomframe = tk.Frame(root, bg='black', bd=5)
bottomframe.place(relx=.1, rely=.7, relheight=.25, relwidth=.8)
leftbutton = tk.Button(bottomframe, text='Hit', command=lambda: hit())
leftbutton.place(relx=0, relwidth=0.4, relheight=1)
def display_array(array):
    n_rows = math.ceil(len(array) / 15)

    window_height = n_rows * 75 + 30
    window_width = 15 * 75

    canvas = tk.Canvas(window, width=window_width, height=window_height)

    for i in range(n_rows + 1):
        y = i * 75
        canvas.create_line(0, y, window_width, y, fill="#476042")

    for i in range(15):
        x = i * 75
        canvas.create_line(x, 0, x, window_height - 30, fill="#476042")

    count = 0
    for i in range(n_rows):
        for j in range(15):
            grid_label = tk.Label(window, text=array[count])
            grid_label.config(font=('helvetica', 11))

            x = (j + 1) * 75 / 2 + (j * 75 / 2)
            y = (i + 1) * 75 / 2 + (i * 75 / 2)
            canvas.create_window(x, y, window=grid_label)

            count += 1

            if count == len(array):
                break

    canvas.pack()

    restart_btn = tk.Button(text='Restart',
                            command=draw_main_window,
                            bg='brown',
                            fg='white',
                            font=('helvetica', 9, 'bold'))
    restart_btn.config(height=1, width=10)
    canvas.create_window(50, window_height - 14, window=restart_btn)

    #Tortoise legend
    canvas.create_rectangle(145,
                            window_height - 20,
                            155,
                            window_height - 10,
                            outline="green",
                            width=3)
    label_tortoise = tk.Label(window, text='Tortoise')
    label_tortoise.config(font=('helvetica', 10))
    canvas.create_window(190, window_height - 15, window=label_tortoise)

    #Hare legend
    canvas.create_rectangle(245,
                            window_height - 20,
                            255,
                            window_height - 10,
                            outline="red",
                            width=3)
    label_hare = tk.Label(window, text='Hare')
    label_hare.config(font=('helvetica', 10))
    canvas.create_window(280, window_height - 15, window=label_hare)

    #Both legend
    canvas.create_rectangle(345,
                            window_height - 20,
                            355,
                            window_height - 10,
                            outline="blue",
                            width=3)
    label_hare = tk.Label(window, text='Both')
    label_hare.config(font=('helvetica', 10))
    canvas.create_window(380, window_height - 15, window=label_hare)

    step_btn = tk.Button(
        text='>',
        command=lambda: find_repeated_occurrence_by_steps(array, canvas),
        bg='green',
        fg='white',
        font=('helvetica', 9, 'bold'))
    step_btn.config(height=1, width=5)
    canvas.create_window(window_width - 150,
                         window_height - 14,
                         window=step_btn)

    start_btn = tk.Button(text='Run',
                          command=lambda: find_repeated_occurrence(array),
                          bg='green',
                          fg='white',
                          font=('helvetica', 9, 'bold'))
    start_btn.config(height=1, width=10)
    canvas.create_window(window_width - 50,
                         window_height - 14,
                         window=start_btn)
Пример #29
0
Файл: env.py Проект: sskett/ffai
    def render(self, feature_layers=False):
        if self.root is None:
            self.root = tk.Tk()
            self.root.title("FFAI Gym")
            self.game_width = max(500, self.game.arena.width*FFAIEnv.square_size)
            self.game_height = self.game.arena.height*FFAIEnv.square_size + FFAIEnv.top_bar_height + FFAIEnv.bot_bar_height
            if feature_layers:
                self.cols = math.floor(math.sqrt(len(self.layers)))
                self.rows = math.ceil(math.sqrt(len(self.layers)))
                self.fl_width = (self.game.arena.width+1) * self.cols * FFAIEnv.square_size_fl + FFAIEnv.square_size_fl
                self.fl_height = ((self.game.arena.height+1) * FFAIEnv.square_size_fl + FFAIEnv.layer_text_height) * self.rows + FFAIEnv.square_size_fl
                self.cv = tk.Canvas(width=max(self.game_width, self.fl_width), height=self.fl_height + self.game_height, master=self.root)
            else:
                self.cv = tk.Canvas(width=self.game_width, height=self.game_height, master=self.root)

        self.cv.pack(side='top', fill='both', expand='yes')
        self.cv.delete("all")
        self.root.configure(background='black')

        if self.game is not None:
            # Squares
            for y in range(self.game.arena.height):
                for x in range(self.game.arena.width):
                    if self.game.arena.board[y][x] == Tile.CROWD:
                        fill = FFAIEnv.crowd
                    elif self.game.arena.board[y][x] in TwoPlayerArena.home_td_tiles:
                        fill = FFAIEnv.blue
                    elif self.game.arena.board[y][x] in TwoPlayerArena.away_td_tiles:
                        fill = FFAIEnv.red
                    elif self.game.arena.board[y][x] in TwoPlayerArena.wing_left_tiles or self.game.arena.board[y][x] in TwoPlayerArena.wing_right_tiles:
                        fill = FFAIEnv.wing
                    elif self.game.arena.board[y][x] in TwoPlayerArena.scrimmage_tiles:
                        fill = FFAIEnv.scrimmage
                    else:
                        fill = FFAIEnv.field
                    self.cv.create_rectangle(FFAIEnv.square_size*x, FFAIEnv.square_size*y + FFAIEnv.top_bar_height, FFAIEnv.square_size*x + FFAIEnv.square_size, FFAIEnv.square_size*y + FFAIEnv.square_size + FFAIEnv.top_bar_height, fill=fill, outline=FFAIEnv.black)

            self.cv.create_line(self.game.arena.width*FFAIEnv.square_size/2.0-1, FFAIEnv.top_bar_height, self.game.arena.width*FFAIEnv.square_size/2.0-1, self.game.arena.height*FFAIEnv.square_size + FFAIEnv.top_bar_height, fill=FFAIEnv.black, width=2)

            # Players
            for y in range(self.game.state.pitch.height):
                for x in range(self.game.state.pitch.width):
                    player = self.game.state.pitch.board[y][x]
                    if player is not None:
                        self._draw_player(player, FFAIEnv.square_size*x, FFAIEnv.square_size*y + FFAIEnv.top_bar_height)

            # Dugouts
            x = 4
            y = self.game.arena.height*FFAIEnv.square_size + FFAIEnv.top_bar_height + 4
            for player in self.game.get_reserves(self.game.state.away_team):
                self._draw_player(player, x, y)
                x += FFAIEnv.square_size
            x = 4
            y += FFAIEnv.square_size
            for player in self.game.get_kods(self.game.state.away_team):
                self._draw_player(player, x, y)
                x += FFAIEnv.square_size
            x = 4
            y += FFAIEnv.square_size
            for player in self.game.get_casualties(self.game.state.away_team):
                self._draw_player(player, x, y)
                x += FFAIEnv.square_size
            x = 4
            y += FFAIEnv.square_size
            for player in self.game.get_dungeon(self.game.state.away_team):
                self._draw_player(player, x, y)
                x += FFAIEnv.square_size

            x = self.game.arena.width*FFAIEnv.square_size - FFAIEnv.square_size
            y = self.game.arena.height * FFAIEnv.square_size + FFAIEnv.top_bar_height + 4
            for player in self.game.get_reserves(self.game.state.home_team):
                self._draw_player(player, x, y)
                x -= FFAIEnv.square_size
            x = self.game.arena.width * FFAIEnv.square_size - FFAIEnv.square_size
            y += FFAIEnv.square_size
            for player in self.game.get_kods(self.game.state.home_team):
                self._draw_player(player, x, y)
                x -= FFAIEnv.square_size
            x = self.game.arena.width * FFAIEnv.square_size - FFAIEnv.square_size
            y += FFAIEnv.square_size
            for player in self.game.get_casualties(self.game.state.home_team):
                self._draw_player(player, x, y)
                x -= FFAIEnv.square_size
            x = self.game.arena.width * FFAIEnv.square_size - FFAIEnv.square_size
            y += FFAIEnv.square_size
            for player in self.game.get_dungeon(self.game.state.home_team):
                self._draw_player(player, x, y)
                x -= FFAIEnv.square_size

            # Ball
            for ball in self.game.state.pitch.balls:
                self.cv.create_oval(FFAIEnv.square_size * ball.position.x + FFAIEnv.square_size/4,
                                    FFAIEnv.square_size * ball.position.y + FFAIEnv.square_size/4 + FFAIEnv.top_bar_height,
                                    FFAIEnv.square_size * ball.position.x + FFAIEnv.square_size - FFAIEnv.square_size/4,
                                    FFAIEnv.square_size * ball.position.y + FFAIEnv.square_size - FFAIEnv.square_size/4 + FFAIEnv.top_bar_height,
                                    fill=FFAIEnv.ball, outline=FFAIEnv.black, width=1)

            # Non-spatial
            self.cv.create_text(self.game.arena.width*FFAIEnv.square_size/2.0, 10, text='Half: {}, Weather: {}'.format(self.game.state.half, self.game.state.weather.name), fill='black')
            self.cv.create_text(self.game.arena.width*FFAIEnv.square_size/2.0, 34, text='{}: Score: {}, Turn: {}, RR: {}/{}, Bribes: {}'.format(
                self.game.state.away_team.name,
                self.game.state.away_team.state.score,
                self.game.state.away_team.state.turn,
                self.game.state.away_team.state.rerolls,
                self.game.state.away_team.state.rerolls_start,
                self.game.state.away_team.state.bribes), fill='blue')
            self.cv.create_text(self.game.arena.width * FFAIEnv.square_size / 2.0, 22,
                                text='{}: Score: {}, Turn: {}, RR: {}/{}, Bribes: {}'.format(
                                    self.game.state.home_team.name,
                                    self.game.state.home_team.state.score,
                                    self.game.state.home_team.state.turn,
                                    self.game.state.home_team.state.rerolls,
                                    self.game.state.home_team.state.rerolls_start,
                                    self.game.state.home_team.state.bribes), fill='red')

        # Feature layers
        if feature_layers:
            row = 0
            col = 0
            for name, grid in self.last_obs['board'].items():
                grid_x = col * (len(grid[0]) + 1) * FFAIEnv.square_size_fl + FFAIEnv.square_size_fl
                grid_y = row * (len(grid) + 1) * FFAIEnv.square_size_fl + self.game_height + FFAIEnv.square_size_fl + ((row+1) * FFAIEnv.layer_text_height)

                self.cv.create_text(grid_x + (len(grid[0]) * FFAIEnv.square_size_fl)/2, grid_y - FFAIEnv.layer_text_height/2, text=name)
                self.cv.create_rectangle(grid_x,
                                         grid_y,
                                         grid_x + len(grid[0]) * FFAIEnv.square_size_fl,
                                         grid_y + len(grid) * FFAIEnv.square_size_fl,
                                         fill='black', outline=FFAIEnv.black, width=2)
                for y in range(len(grid)):
                    for x in range(len(grid[0])):
                        value = 1 - grid[y][x]
                        fill = '#%02x%02x%02x' % (int(value * 255), int(value * 255), int(value * 255))
                        self.cv.create_rectangle(FFAIEnv.square_size_fl * x + grid_x,
                                                 FFAIEnv.square_size_fl * y + grid_y,
                                                 FFAIEnv.square_size_fl * x + grid_x + FFAIEnv.square_size_fl,
                                                 FFAIEnv.square_size_fl * y + grid_y + FFAIEnv.square_size_fl,
                                                 fill=fill, outline=FFAIEnv.black)
                col += 1
                if col >= self.cols:
                    col = 0
                    row += 1

        self.root.update_idletasks()
        self.root.update()
Пример #30
0
# -*- encoding: utf-8 -*-
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
import random
import math
import sys
from geopy.distance import geodesic

from ga import ga

window = tk.Tk()
window.title = ("TSP")
window.geometry('1600x1600')
canvas = tk.Canvas(window, bg="white", height='600', width="700")
img_open = Image.open('map.jpg')
img_jpg = ImageTk.PhotoImage(img_open)
canvas.create_image(0, 0, anchor='nw', image=img_jpg)
canvas.pack()


class TSP_WIN(object):
    def __init__(self):
        self.window = window
        self.citys = [['西安', 108.95, 34.27], ['北京', 116.46, 39.92],
                      ['南京', 118.78, 32.04], ['广州', 113.23, 23.16],
                      ['成都', 104.06, 30.67], ['武汉', 114.31, 30.52],
                      ['兰州', 103.73, 36.03], ['昆明', 102.73, 25.04],
                      ['拉萨', 91.11, 29.97], ['上海', 121.48, 31.22]]
        self.position = [[414, 299], [474, 192], [522, 306], [500, 455],
                         [324, 346], [474, 358], [353, 280], [317, 442],